说明 | |
---|---|
首次发布 | 2018年12月23日 |
最近更新 | 2019年04月07日 |
block 书写
作为本地变量:
格式:
returnType (^blockName)(paramType param...) = ^returnType(paramType param...) {
return ...
};
例如:
NSInteger (^getSum)(NSInteger a, NSInteger b) = ^NSInteger(NSInteger a, NSInteger b) {
return a + b;
};
NSLog(@"%ld", getSum(1, 2)); //打印3
作为属性
格式:
@property (nonatomic, copy) returnType (^blockName)(paramType param);
例如:
@property (nonatomic, copy) void (^blockName)(NSString *paramName);
作为方法参数
格式:
- (void)someMethodThatTakesABlock:(returnType (^)(paramType param))blockName;
例如:
- (void)doSomethingWithBlock:(void(^)(NSString *name))block {
}
用作typedef
格式:
typedef returnType (^TypeName)(paramType param);
TypeName blockName = ^returnType(parameters) {...};
例如:
typedef NSInteger (^GetSumWithDef)(NSInteger a, NSInteger b);
GetSumWithDef block = ^NSInteger(NSInteger a, NSInteger b) {
return a + b;
};
NSLog(@"%ld", block(2, 2)); //打印4
block的传值和传址
先看下面四个例子:
void testBlockOne() {
static NSInteger a = 10;
void (^staticBlock)(void) = ^{
NSLog(@"a is %ld", a);
};
a = 20;
staticBlock(); // 20
}
void testBlockTwo() {
__block NSInteger b = 10;
void (^blockBlock)(void) = ^{
NSLog(@"b is %ld", b);
};
b = 20;
blockBlock(); // 20
}
NSInteger c = 10;
void testBlockThree() {
void (^globalVarialBlock)(void) = ^{
NSLog(@"c is %ld", c);
};
c = 20;
globalVarialBlock(); // 20
}
void testBlockFour() {
NSInteger d = 10;
void (^commonBlock)(void) = ^{
NSLog(@"d is %ld", d);
};
d = 20;
commonBlock(); // 10
}
造成这样的原因就是:传址 和 传值。具体请自行把 .m 编译成 C++代码,查看得到的 .cpp 文件。
总结:
__block
、static
和 全局变量
都是 传址,只有 普通局部变量
是 传值。