【发布时间】:2013-03-23 20:13:18
【问题描述】:
我看到了一些关于在 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);
});
哪个更好用?后者的简单性是否存在固有的错误?
【问题讨论】:
-
第二个更简单,可能更难搞砸,尤其是当你处理大量请求时。不像第一个那样灵活。
标签: ios objective-c xcode json