Block代替delegate,尽量使用block,对于有大量的delegate方法才考虑使用protocol实现.
1.Block语法总结及示例如下:
//1.普通代码块方式block
returnType (^blockName)(parameterTypes) = ^returnType(parameters) {
// block code
};
使用未例:
int (^abc)(int a) = ^int(int a){
return a+1;
};
int aa = abc(2);
NSLog(@"%d",aa);
//2.属性方式block
@property (nonatomic, copy) returnType (^blockName)(parameterTypes);
使用示例:
1.定义属性
@property (nonatomic,copy) int (^testblock)(NSString *);
2.设置使用属性
[self setTestblock:^int(NSString *a) {
return 0;
}];
//3.方法参数block
- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName {
// block code
};
使用示例1:
1.无参数型定义及实现:
- (void)testBlockFun:(void(^)())completion{
NSLog(@"执行");
if (completion) {
completion();
}
}
2.无参数型block调用:
[self testBlockFun:^{
NSLog(@"回调结束");
}];
使用示例2:
1.带参数型定义及实现:
- (void)testBlockFun:(int (^)(int a,int b))complate{
if (complate) {
int c = complate(3,5);
NSLog(@"c:%d",c);
}
}
2.带参数型block调用:
[self testBlockFun:^int(int a, int b) {
return a+b;
}];
// 4.作为参数
[someObject someMethodThatTakesABlock: ^returnType (parameters) {
// block code
}];
使用示例:
1.定义及实现
- (void) testBlockFun:(void (^)(NSString *))complate{
if (complate) {
complate(@"success");
}
}
2.调用
[self testBlockFun:^(NSString *str) {
NSLog(@"str:%@",str);
}];
// 5.使用 typedef 定义
typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^(parameters) {
};
使用示例:
typedef void (^blockTestName)(NSString *);
调用:
[self setName:^(NSString *a){
}];
2.Block修改值:使用__block可以在block内部修改外部变量的值。
__block int someIncrementer = 0;
[someObject someMethodThatTakesABlock:^{
someIncrementer++;
}];
3.Block循环引用,block会持有对象,block的对象也有block,会造成block的循环引用,解决方法:
__weak typeof(self) weakSelf = self;//@weakify(self);
[self someMethodThatTakesABlock:^{
[weakSelf action];
}];