使用块的目的是什么?

26

我希望在我的应用程序中使用blocks,但我不太了解有关blocks的任何信息。有人可以解释一下我应该如何以及为什么要在我的代码中使用blocks吗?


3
它们可以让你的生活变得更加轻松! - Mick MacCallum
2
就像JavaScript中的闭包一样。你可以传递的代码片段。 - Thilo
2
他们帮助我避免为每个回调编写委托方法。 - Kaan Dedeoglu
在Paul Hegarty的iOS开发课程中,可以了解更多相关信息,请参考第8讲(11:19) - danielhadar
3个回答

30

块是闭包(或lambda函数),你可以按照自己的喜好来称呼它们。它们的目的是使用块,程序员不必在全局范围内创建命名函数或提供目标-动作回调,而是可以创建一个未命名的本地“函数”,该函数可以访问其封闭范围内的变量并轻松执行操作。

例如,如果你想要分发异步操作,比如为视图添加动画效果,并且希望在完成时得到通知,那么如果没有块,你需要编写以下代码:

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

这是一大段代码,而且它暗示了一个有效的self指针 - 这可能并不总是可用的(我在开发MobileSubstrate-tweaks时遇到过这样的情况)。因此,您可以使用iOS 4.0及以上版本中的块代替:

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

比如,使用NSURLConnection加载在线资源...B. b. (块之前):

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
}];

更简单、更清洁、更短。


14

引用Ray Wenderlich教程

块(block)是一种第一类函数,这就是说块是常规的Objective-C对象。由于它们是对象,因此它们可以作为参数传递、从方法和函数中返回,并赋值给变量。在其他语言(如Python、Ruby和Lisp)中,块被称为闭包(closures),因为它们在声明时封装了状态。块会创建任何本地变量的常量副本,这些本地变量在其范围内被引用。在引入块之前,每当你想要调用一些代码并稍后回调时,通常会使用委托或NSNotificationCenter。虽然这种方法有效,但代码分散到各处 - 你在一个地方开始一个任务,而在另一个地方处理结果。

例如,使用块进行视图动画将使您免于手动执行以下所有步骤:

[UIView beginAnimations:@"myAnimation" context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.5];
[myView setFrame:CGRectMake(30, 45, 43, 56)];
[UIView commitAnimations];

只需要这样做:

[UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
    [myView setFrame:CGRectMake(54, 66, 88, 33)];
}completion:^(BOOL done){
    //
}];

0
一个Objective-C类定义了一个将数据与相关行为结合起来的对象。有时,仅表示单个任务或行为单元而不是一组方法是有意义的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接