我看到了几个关于在 iOS 中发出 JSON 请求的教程,其中许多使用 NSURLConnection 列出了类似这样的内容:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {}
但是我今天读了另一个教程(http://mobile.tutsplus.com/tutorials/iphone/ios-quick-tip-interacting-with-web-services/),它有这个非常简单的实现:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:@"http://brandontreb.com/apps/pocket-mud-pro/promo.json"];
NSString *json = [NSString stringWithContentsOfURL:url
encoding:NSASCIIStringEncoding
error:&error];
NSLog(@"\nJSON: %@ \n Error: %@", json, error);
});
哪个更好用?后者的简单性是否存在固有的错误?