Objective-C中的方法和块之间的区别

Bal*_*cze 4 methods objective-c-blocks

我对编程还比较陌生,有一件事我无法缠住手。也就是说,什么是块?为什么/何时使用它们?块和方法有什么区别?在我看来,他们似乎在做同样的事情。

可以给我解释一下吗?

是的,我确实在Google上花费了数小时,才终于来这里询问。

iDe*_*750 5

  • 块是匿名函数。
  • 块用于以后执行,但功能不能用于以后执行。
  • 块通常用于回叫(无需使用委托)
  • 块是对象,但功能不是对象。

假设您想执行类似动画的操作,并且希望在完成后得到通知。然后,您必须编写以下代码:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:context:)];
[UIView commitAnimations];
Run Code Online (Sandbox Code Playgroud)

但是,如果使用如下所示的块,则需要几行代码:

[UIView animateWithDuration:2.0 animations:^{
// set up animation
} completion:^{
// this will be executed on completion
}];
Run Code Online (Sandbox Code Playgroud)

希望您现在对块的使用有所了解。