Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a completion block from a delegate method

It's hard to explain, but basically what I am trying to do is call a completion handler in a block-based method from a delegate method.

I have the method where I call the upload function.

[[UploadManager sharedManager] uploadFile:@"/Path/To/Image.png" success:^(NSDictionary *response) {
    NSLog(@"Uploaded");
}];

Inside of the UpLoad manager, the method performs all the necessary actions to upload the file.

There is a delegate method that I want to call the success block from.

- (void)fileDidUploadAndReceiveData:(NSData *)data {
    NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&parseError];
    // Call the completion method
    success(response);
}

success is defined in the uploadFile method. How would I go about calling this completion handler?

I wrote this late at night so if it doesn't make sense, let me know.

Thanks

like image 660
Anthony Castelli Avatar asked Dec 16 '22 00:12

Anthony Castelli


1 Answers

Declare a property that is a copy of the block:

@property(nonatomic, copy) void (^completionBlock)(NSDictionary *);

Assign it in uploadFile:

- (void)uploadFile:(NSString *)url success:(void (^)(NSDictionary *))completionBlock {
    self.completionBlock = completionBlock;
    // ...

Then call it whenever you want:

if (self.completionBlock) self.completionBlock(someDictionary);
self.completionBlock = nil;  // see below

Remember that, if you don't need the block again (which you probably don't since the download is complete) that it's a good practice to nil out your copy of the block. This way, if the caller refers to the download manager within the block, you'll break the retain cycle for him (the block would retain the download manager which retains the block).

like image 163
danh Avatar answered Feb 02 '23 14:02

danh