当您只做一次工作而轻松地将处理程序分批调用时,它们就像调用一个处理程序一样调用它们。
//Create a manager
self.manager = [BHManager new];
//––––––––––––––––––––––––––––––––––––––––––––––––––
//Later when a method with a handler is called...
//––––––––––––––––––––––––––––––––––––––––––––––––––
- (void)doAsyncWork:(void(^)(id result, NSError *error)handler
{
//Any cache checking goes here...
//The manager returns an array that will contain all the handlers to call.
NSArray *handlers = BHManagerAddHandler(self.manager,handler,NSStringFromSelector(_cmd)); //We use the selector as a key
//Continue only if an array is returned
if (!handlers) {
return;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//Do async work
for(typeof(handler) aHandler in handlers) {
aHandler(result, error);
}
});
}
如果想要接受 NULL 处理程序,则必须事先注册一个样本块。
//Note this block is never executed nor does it need to do anything,
//just be of the same interface as the passed handlers
[self.manager setSampleHandler:^(id r, NSError *e){}
forKey:NSStringFromSelector(@selector(doAsyncWork:))];
BatchedHandlers 可通过 CocoaPods 获得。安装它,只需将以下行添加到您的 Podfile 中
pod "BatchedHandlers"