Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

objective c - What is the purpose of using blocks

I want to use blocks in my application, but I don't really know anything about blocks. Can anyone explain how and why I should use blocks in my code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Blocks are closures (or lambda functions, however you like to call them). Their purpose is that using blocks, the programmer doesn't have to create named functions in the global scope or provide a target-action callback, instead he/she can create an unnamed, local "function" which can access the variables in its enclosing scope and easily perform actions.

For example, when you want to e. g. dispatch an asynchronous operation, such an animation for views, without blocks, and you wanted to be notified of the competion, you had to write:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:context:)];
.... set up animation ....
[UIView commitAnimations];

This is a lot of code, furthermore it implies the presence of a valid self pointer - that might not always be available (I experience such a thing when I was developing MobileSubstrate-tweaks). So, instead of this, you can use blocks from iOS 4.0 and onwards:

[UIView animateWithDuration:1.0 animations:^{
    // set up animation
} completion:^{
    // this will be executed on completion
}];

Or, for example, loading online resources with NSURLConnection... B. b. (Before Blocks):

urlConnection.delegate = self;

- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)rsp
{
    // ...
}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
    // ...
}

// and so on, there are 4 or 5 delegate methods...

A. B. (Anno Blocks):

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rsp, NSData *d, NSError *e) {
   // process request here
}];

Much easier, cleaner and shorter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...