如何处理类之间的完成块的结果

时间:2014-12-17 20:31:35

标签: ios objective-c delegates objective-c-blocks completion

我们说我有一个班级UploadManager,我在ViewController创建了一个实例。 UploadManager.m有一个方法-(void)requestData

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

现在,我可以在requestData中的UploadManager实例中调用ViewController.m方法,但我想对responseObject内的ViewController.m做一些事情。一旦完成块被触发,{1}}这样做的最佳方法是什么?我假设我可以制作代理方法,但我想知道是否有更好的解决方案。感谢。

2 个答案:

答案 0 :(得分:3)

您可以使用块结构

   -(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];
    }

在另一个班级

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

答案 1 :(得分:1)

基于块的方法肯定会奏效。如果您想要替代块的方法,可以使用NSNotifications,如下所示:

-(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];
}

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
}