脱离Xcode直接手写一个Block,很多时候还真不一定每次都写得对。
常用定义形式共有以下几种:
// 宏定义Block
typedef NSString* (BlockName)(NSString *param1, NSString *param2);
BlockName block = ^NSString* (NSString *param1, NSString *param2){
...
return...
};
// 声明一个局部Block
NSString * (BlockName)(NSString *param) = ^ NSString* (NSString *param){
...
return...
};
// 声明一个Block属性变量
@property (nonatomic, copy) NSString * ( ^BlockName )(NSString *param1, NSString *param2);
// Block作为方法的入参数
- (void) someMethodThatTakesBlock:( NSString * (^)(NSString *param) )block;
// Block作为方法的回调对象
[someObj someMethodThatTakesBlock: ^ (NSString *param){
...
// void型block,无返回值
}];
链式调用中的block:
//// .h
@interface CustomView : UIView
+ (CustomView *)initCustomView:(void(^)(CustomView *custom))block;
- (CustomView *(^)(CGRect))viewFrame;
- (CustomView *(^)(UIColor *))viewColor;
@end
//// .m
@implementation CustomView
+ (CustomView *)initCustomView:(void (^)(CustomView * _Nonnull))block {
CustomView *custom = [[CustomView alloc] init];
if (block) {
block(custom);
}
return custom;
}
- (CustomView *(^)(CGRect))viewFrame {
CustomView *(^frameBlock)(CGRect frame) = ^CustomView *(CGRect frame){
self.frame = frame;
return self;
};
return frameBlock;
return ^CustomView *(CGRect frame){
self.frame = frame;
return self;
};
}
- (CustomView *(^)(UIColor *))viewColor {
return ^CustomView *(UIColor *color){
self.backgroundColor = color;
return self;
};
}
@end
网友评论