如何声明、定义一个Block
作为局部变量
returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};
例如:int (^addByOneBlock)(int) = ^int(int number) { return number + 1; }
作为属性
@property (nonatomic, copy, nullability) returnType (^blockName)(parameterTypes);
例如:@property (nonatomic, assign) int (^addByOneBlock)(int)
作为方法参数(声明)
(void)someMethodThatTakesABlock:(returnType (^nullability)(parameterTypes))blockName;
例如:(void)someMethod:(int (^)(int))addByOneBlock;
方法调用的参数(调用)
[someObject someMethodThatTakesABlock:^returnType (parameters) {...}];
例如:[someObject someMethod:^int (int number) { return number + 1; }];
typedef
1
2typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters) {...};
例如:1
2
3
4
5typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType);
typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache);
typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize);
1 | ^ 返回值类型 (参数列表) { 表达式 } | | 省略 返回值类型 | ^ (参数列表) { 表达式 } | | 当不使用参数时,可以省略 (参数列表) | ^ { 表达式 } ------------------- Example: ^int (int count) { return count + 1; } | | | ^(int count) { return count + 1; } | | | ^ { NSLog(@"HelloWorld!"); } |