一般用法
结果外传
- 声明
@interface HeaderView : UIView
/// header touch call back
@property (nonatomic, copy) void(^touchCallBack)(NSInteger uid);
@end
- 外传
- (void)headerViewIsTocuh {
if (self.headerTouchCallBack) {
self.headerTouchCallBack(self.uid);
}
}
- 实现
- (HeaderView *)headerView {
if (_headerView == nil) {
_headerView = [[HeaderView alloc]init];
__weak typeof(self) weakSelf = self;
_headerView.touchCallBack = ^(NSInteger uid) {
/// 事件处理
};
}
return _headerView;
}
可适当使用block,将事件结果外传。
其它用法
参数外传
- 声明
@interface Worker : NSObject
+ (void)work:(void(^)(WorkerConfig *config))request success:(void(^)(id result))success failure:(void(^)( NSError *error))failure;
@end
@interface WorkerConfig : NSObject
@property (nonatomic, assign) NSInteger uid;
@end
- 外传
+ (void)work:(void(^)(WorkerConfig *config))request success:(void(^)(id result))success failure:(void(^)( NSError *error))failure {
__block WorkerConfig *config = [[WorkerConfig alloc]init];
if (request) {
request(config);
}
/// 根据config做逻辑处理
/// ...
if (success) {
}
if (failure) {
}
}
- 实现
__weak typeof(self) weakSelf = self;
[Worker work:^(WorkerConfig *config) {
/// 配置config
config.uid = 1;
} success:^(id result) {
///
} failure:^(NSError *error) {
///
}];
固化参数,外部只需对固化的参数进行赋值即可。
双向block
- 声明
@interface HeaderView : UIView
/// header touch call back
@property (nonatomic, copy) void(^ headerTouchCallBack)(NSInteger uid, void(^result)(NSDictionary *data));
@end
- 外传
- (void)headerViewIsTocuh {
if (self.headerTouchCallBack) {
/// 外传uid
self.headerTouchCallBack(self.uid, ^(NSDictionary *data) {
/// 处理接收的data数据
});
}
}
- 实现
- (HeaderView *)headerView {
if (_headerView == nil) {
_headerView = [[HeaderView alloc]init];
__weak typeof(self) weakSelf = self;
_headerView.touchCallBack = ^(NSInteger uid, void (^result)(NSDictionary *data)) {
/// 接收uid并进行处理
/// ...
/// 处理结果反向block
if (result) {
result(x);
}
};
}
return _headerView;
}
双向block,可使逻辑变的更简单,尤其是依赖外传操作结果时。
特殊用法
delegate + block
一般,delegate事件外传,其结果,需要同步返回。但当需要异步执行操作,如何通过delegate一个方法,即可拿到结果回调呢?delegate+block?可实现,但用法比较偏。
网友评论