7

在编写库时,我需要将来自 AFNetworking 调用的响应封装在我自己的方法中。这段代码让我很接近:

MyDevice *devices = [[MyDevice alloc] init];
  [devices getDevices:@"devices.json?user_id=10" success:^(AFHTTPRequestOperation *operation, id responseObject) {

    ... can process json object here ...

}

 - (void)getDevices:(NSString *)netPath success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure {
    [[MyApiClient sharedDeviceServiceInstance] getPath:[NSString stringWithFormat:@"%@", netPath]
      parameters:nil success:success  failure:failure];
}

但是,我需要在返回 getDevices() 之前处理从 getPath 返回的 json 对象数据。我试过这个:

- (void)getDevices:(NSString *)netPath success:(void (^)(id  myResults))success
        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure {

  [[MyApiClient sharedDeviceServiceInstance] getPath:[NSString stringWithFormat:@"%@", netPath]
    parameters:nil
    success:^(AFHTTPRequestOperation *operation, id responseObject)
   {
     ... can process json object here ...
   }                           
   failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     ... process errors here ...
   }];
}

但是现在没有回调 getDevices()。那么如何处理 getDevices 中的 json 对象并在完成时返回块?感谢您的帮助,因为我是块新手。

4

1 回答 1

10

这很容易做到:只需像函数一样调用块来调用它。

- (void)getDevices:(NSString *)netPath 
           success:(void (^)(id  myResults))success
           failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure
{
  [[MyApiClient sharedDeviceServiceInstance] 
     getPath:netPath
  parameters:nil
     success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
       id myResults = nil;
       // ... can process json object here ...
       success(myResults);
     }                           
     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       // ... process errors here ...
       failure(operation, error);
     }];
}

编辑:

根据您发布的代码,我认为以下界面会更清晰:

typedef void(^tFailureBlock)(NSError *error);

- (void)getDevicesForUserID:(NSString *)userID 
                    success:(void (^)(NSArray* devices))successBlock
                    failure:(tFailureBlock)failureBlock;
于 2012-06-22T20:37:32.820 回答