Objective c 使用多线程加载JSON数据
我想通过多线程加载JSON数据并将其解析到NSDictionary,之前使用twitter提要的TWRequest类完成了这项工作,我如何使用NSURLRequest执行以下操作:Objective c 使用多线程加载JSON数据,objective-c,ios,ios5,grand-central-dispatch,nsurlrequest,Objective C,Ios,Ios5,Grand Central Dispatch,Nsurlrequest,我想通过多线程加载JSON数据并将其解析到NSDictionary,之前使用twitter提要的TWRequest类完成了这项工作,我如何使用NSURLRequest执行以下操作: TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString: @"https://api.twitter.com/1/statuses/public_timeline.json?screen_name=firdous_ali86&a
TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString: @"https://api.twitter.com/1/statuses/public_timeline.json?screen_name=firdous_ali86&include_entities=true"] parameters:nil requestMethod:TWRequestMethodGET];
// Notice this is a block, it is the handler to process the response
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if ([urlResponse statusCode] == 200)
{
tweetCollection = [[NSMutableArray alloc] init];
Tweet *tweet;
NSError *error;
NSArray *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
}
}];
问题是NSURLRequest没有实现performRequestWithHandler方法。这是我本周最流行的答案。看看苹果的文档 答案就在那里
在出现堆栈溢出之前,是否有人阅读了文档?您始终可以创建一个委托,并让该委托在完成后回调,或者使用
NSURLConnection的connection did finish loading delegate方法来处理推特响应。或者最好使用ASIHTTPRequest
或AFNetwork
框架使请求异步,然后执行JSON
解析您可以使用NSURLConnection
方法:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
我用过:
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString: @"http://my_service_url"] //2
- (void)viewDidLoad
{
myCollection = [[NSMutableArray alloc] init];
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
NSError* error;
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:data //1
options:kNilOptions
error:&error];
NSArray* myArray = [jsonDict objectForKey:@"response"]; //2
NSEnumerator *myIterator = [myArray objectEnumerator];
id anObject;
Cast *cast;
while( anObject = [myIterator nextObject])
{
cast = [[Cast alloc] init];
cast.castTitle = [anObject objectForKey:@"castTitle"];
[myCollection addObject:cast];
}
[myTableView reloadData];
});
}
我没有看到在那里使用块,也没有使用performRequestWithHandler方法的替代方法。我认为应该从主线程调用reloadData tableView方法。在apple文档中,您可以发现:注意:在大多数情况下,UIKit类只能从应用程序的主线程使用。对于从UIResponder派生的类或涉及以任何方式操纵应用程序用户界面的类来说,这一点尤其正确。有关更多详细信息,请参阅。