如何重用obj-c块?

时间:2014-08-04 07:35:50

标签: objective-c objective-c-blocks

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://aaa"
    success:^(AFHTTPRequestOperation *operation, id responseJSON) {
      ...
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[TWMessageBarManager sharedInstance]
            showMessageWithTitle:@"Network connection failure"
                     description:@"Please check your network"
                            type:TWMessageBarMessageTypeError];
    }];

某些块是常量,可以重复使用。例如,这里是故障块,如何重用此块来减少代码量?

我希望它是全局重用,而不是当前的上下文,所以我可以将它存储为属性?或get_method()?

3 个答案:

答案 0 :(得分:3)

你可以像它一样保存它:

void(^blockname)(AFHTTPRequestOperation*, NSError*) = ^(AFHTTPRequestOperation *operation, NSError *error) {
    [[TWMessageBarManager sharedInstance]
        showMessageWithTitle:@"Network connection failure"
                 description:@"Please check your network"
                        type:TWMessageBarMessageTypeError];
}

然后只将blockname放入失败参数而不是整个

答案 1 :(得分:3)

将块保存到变量,然后您可以传递它:

void (^failureBlock)(AFHTTPRequestOperation *operation, NSError *error) = ^void(AFHTTPRequestOperation *operation, NSError *error) { /* write what you want */ };

void (^successBlock)(AFHTTPRequestOperation *operation, id responseJSON) = ^void(AFHTTPRequestOperation *operation, id responseJSON) { /* write what you want */ };

然后你可以在这样的进一步调用中使用它:

[manager GET:@"" success:successBlock failure: failureBlock];

奖金:Check out this guide

答案 2 :(得分:1)

另一种方法,而不是重用块,您应该考虑重用整个函数

- (void)getURLPath:(NSString *)urlPath withSuccessBlock:(void (^)(id responseJSON))block {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:urlPath
    success:^(AFHTTPRequestOperation *operation, id responseJSON) {
      ...
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[TWMessageBarManager sharedInstance]
            showMessageWithTitle:@"Network connection failure"
                     description:@"Please check your network"
                            type:TWMessageBarMessageTypeError];
    }];
}