0

假设我有一个类UploadManager,我在我的ViewController. UploadManager.m有方法-(void)requestData

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

现在我可以从我的inrequestData实例调用该方法,但是一旦完成块被触发,我想在内部做一些事情。这样做的最佳方法是什么?我想我可以制作一个委托方法,但我想知道是否有更好的解决方案。谢谢。UploadManagerViewController.mresponseObjectViewController.m

4

2 回答 2

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
    }];
于 2014-12-17T20:43:58.803 回答
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
}
于 2014-12-17T22:18:19.370 回答