Ben*_*n10 25 cocoa-touch block objective-c objective-c-blocks
我想在我的应用程序中使用块,但我对块没有任何了解.任何人都可以解释为什么我应该在我的代码中使用块?
小智 30
块是闭包(或lambda函数,但你喜欢称它们).它们的目的是使用块,程序员不必在全局范围内创建命名函数或提供目标操作回调,而是他/她可以创建一个未命名的本地"函数",它可以访问其封闭的变量范围并轻松执行操作.
例如,当您想要例如调度异步操作,这样的视图动画,没有块,并且您想要获得竞争通知时,您必须写:
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:context:)];
.... set up animation ....
[UIView commitAnimations];
Run Code Online (Sandbox Code Playgroud)
这是很多代码,而且它意味着存在一个有效的self指针 - 可能并不总是可用(我在开发MobileSubstrate-tweaks时经历过这样的事情).因此,您可以使用iOS 4.0及更高版本中的块,而不是这样:
[UIView animateWithDuration:1.0 animations:^{
// set up animation
} completion:^{
// this will be executed on completion
}];
Run Code Online (Sandbox Code Playgroud)
或者,例如,使用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...
Run Code Online (Sandbox Code Playgroud)
AB(Anno Blocks):
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rsp, NSData *d, NSError *e) {
// process request here
}];
Run Code Online (Sandbox Code Playgroud)
更简单,更清洁,更短.
Mic*_*lum 14
块是一流的函数,这是一种说明Blocks是常规Objective-C对象的奇特方式.由于它们是对象,因此可以作为参数传递,从方法和函数返回,并分配给变量.块在其他语言中称为闭包,例如Python,Ruby和Lisp,因为它们在声明时封装了状态.块创建在其作用域内引用的任何局部变量的const副本.在块之前,只要您想调用某些代码并让它稍后再调用,您通常会使用委托或NSNotificationCenter.这很好,除了它遍布你的代码 - 你在一个地方开始一个任务,并在另一个地方处理结果.
例如,在视图中使用块的动画使您无需执行所有操作:
[UIView beginAnimations:@"myAnimation" context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.5];
[myView setFrame:CGRectMake(30, 45, 43, 56)];
[UIView commitAnimations];
Run Code Online (Sandbox Code Playgroud)
只需要这样做:
[UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
[myView setFrame:CGRectMake(54, 66, 88, 33)];
}completion:^(BOOL done){
//
}];
Run Code Online (Sandbox Code Playgroud)