当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - 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.

网友答案:

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
    }];
网友答案:

The block-based approach will certainly work. If you want an alternate approach to blocks, you could use NSNotifications as follows:

-(void)requestDataWithHandler:(void (^)(id responseObject))handler
{
    HTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] init];
    [operation setCompletionBlockWithSuccess:^(HTTPRequestOperation *operation, id responseObject){
        // You'll probably want to define the Notification name elsewhere instead of saying @"Information updated" below.
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Information updated" object:nil];
    }];
    [operation start];
}

Elsewhere in ViewController.m:

- (void)viewDidLoad
{
  [super viewDidLoad];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomethingUponUpdate) name:@"Information updated" object:nil];
}

-(void)dealloc
{ 
  // Don't forget to remove the observer, or things will get unpleasant
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)doSomethingUponUpdate
{
  // Something
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: