I’m diving into iOS programming and I’m learning how to use blocks. I have a sucky, over-engineered library that I’m using in my project and it uses a single callback method to handle all data requests…
@protocol SuckyClassDelegate <NSObject>
-(void)returnedSuckyData:(NSMutableDictionary*)data;
@end
@interface SuckyClass: NSObject
@property (nonatomic, weak) id<SuckyClassDelegate> delegate;
-(void)getSuckyData;
@end
@interface MyViewController: UIViewController <SuckyClassDelegate>
-(void)requestDataFromSuckyClass;
@end
I’d like to create a wrapper class for the SuckyClass that allows me to use blocks when I need to access data from the SuckyClass, but I don’t know how to do this. I’d like to have something like this…
@interface SuckyClassWrapper
- (void)requestDataWithSuccessBlock:(void(^)((NSMutableDictionary*)data))successBlock;
@end
@implementation MyViewController
-(void)requestDataFromSuckyClass {
SuckyClassWrapper *wrapper = [[SuckyClassWrapper alloc] init];
[wrapper requestDataWithSuccessBlock:^(NSMutableDictionary *data) {
NSLog(@"%@", data);
}
}
@end
…but I can’t figure out how to convert the callback process into blocks. Can anyhow give me some direction here?
Thanks in advance for your wisdom!
By the way, I just whipped up the code without testing it, so I apologize if there are any typos.
The trick is to copy the completion block to a class iVar that you can then call later.
Here is a method that saves two blocks for use later and then calls another class method:
Later – when what we want to do has completed, we have another method that we call to run the blocks. In this silly example code we check to see if a class property
self.errorisnil. If it is notnil, we send that error to our saved error block. If it isnil, we passself.datato the success block.