在使用远程REST API时最好处理异步调用

时间:2014-02-14 15:41:45

标签: ios objective-c asynchronous synchronous

我想听听围绕使用后端API /服务的iOS客户端的各种设计注意事项。具体来说,客户端中的哪个位置最好离开异步线程管理?

我到目前为止采用的方法是让API包装器类同步处理所有请求,然后让调用类处理异步线程管理。我以异步方式处理与后端的交互的主要目标是平滑用户体验(与性能的并行处理等)。

所以使用这种方法,我们有API包装类:

@implementation APIWrapper

- (NSDictionary *)getRecord (NSNumber *)recordId {
  NSDictionary *record = nil;
  NSString *url = @"http://myhost/api/records";
  NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
  NSHTTPURLResponse *response = nil;
  NSError *error = nil;
  NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  if (responseData != nil) {
    record = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
  }
  return record;
}

@end

和处理异步线程管理的消费类(我们将记录放入UITableView:

...
  self.recordsQ = [[NSOperationQueue alloc] init];
...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  ...
  NSDictionary *record = nil;
  [self.recordsQ addOperationWithBlock:^{
    record = [self.apiWrapper getRecord:recordId];
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
    if (record != nil) {
      [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        cell.textLabel.text = record objectForKey:@"name";
      }];
    }
  }];
  ...
  return cell;
}

另一种方法似乎是使用[NSURLConnection sendAsynchronousRequest]completionHandler块,我自己没有用过。

这两种用途有哪些优点/缺点/考虑因素?

另外,我一般都对我一直采用的当前同步方法的评论/改进持开放态度。

1 个答案:

答案 0 :(得分:0)

你绝对应该使用[NSURLConnection sendAsynchronousRequest]。您可能还想考虑使用AFNetworking这样的框架,它已经提供了很好的类来包装NSOperations中的请求。