在Objective-C中使用块而不是普通方法和函数有什么好处?我已经阅读了文档,但是我找不到块的具体用法而不是其他语言功能.
我确信我错过了一些东西,那么有人能以比现有文档更简单的方式解释块的优点吗?
我如何创建自己的方法,将块作为参数,以后可以调用?
我试过以下事情.
#import <UIKit/UIKit.h>
typedef void (^viewCreator)(void);
@interface blocks2ViewController : UIViewController
{
}
-(void)createButtonUsingBlocks:(viewCreator *)block;
@end
- (void)viewDidLoad {
[super viewDidLoad];
[self createButtonUsingBlocks:^(NSString * name) {
UIButton *dummyButton = [[UIButton alloc]initWithFrame:CGRectMake(50, 50, 200, 100)];
dummyButton.backgroundColor = [UIColor greenColor];
[self.view addSubview:dummyButton];
}];
}
-(void)createButtonUsingBlocks:(viewCreator *)block
{
// Do something
NSLog(@"inside creator");
}
Run Code Online (Sandbox Code Playgroud)
我也尝试将块变量传递给我的自定义方法,但没有任何成功.为什么会这样,做正确的方法是什么?
更新
这是文件is.h:
#import <UIKit/UIKit.h>
typedef void (^viewCreator)(void);
@interface blocks2ViewController : UIViewController
{
}
- (void)createButtonUsingBlocks:(viewCreator)block;
@end
Run Code Online (Sandbox Code Playgroud)
这是.m文件:
#import "blocks2ViewController.h"
@implementation blocks2ViewController
// Implement viewDidLoad …Run Code Online (Sandbox Code Playgroud)