Search code examples
iosobjective-cdelegatesobjective-c-blockscompletion

How to handle the result of a completion block between classes


Let's say I have a class UploadManager and I create an instance of it in my ViewController. UploadManager.m has a method -(void)requestData

-(void)requestData
{
    HTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] init];
    [operation setCompletionBlockWithSuccess:^(HTTPRequestOperation *operation, id responseObject){
        // Do something here
    }];
    [operation start];
}

Now I can call the requestData method from my instance of UploadManager in ViewController.m, but I'd like to do something with the responseObject inside of ViewController.m once the completion block has fired. What's the best way of doing this? I assume I could make a delegate method but I'm wondering if there's a better solution. Thanks.


Solution

  • You can use blocks structure for that

       -(void)requestDataWithHandler:(void (^)(id responceObject))handler
        {
            HTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] init];
            [operation setCompletionBlockWithSuccess:^(HTTPRequestOperation *operation, id responseObject){
                // Do something here
    
            if(handler)
            {
               handler(responceObject)
            }
            }];
            [operation start];
        }
    

    In another class

     [uploadManager requestDataWithHandler:^(responceObject) {
        // here work with responeObject
        }];