【发布时间】:2015-07-27 19:00:22
【问题描述】:
最近我开始为 iOS 开发并遇到问题,这对您来说可能很明显,但我自己无法解决。 我要做的是使用 GCD 提供的多线程来执行另一个任务。
这是我获取 JSON 的代码(与单例一起放入类中) 分类商店
- (instancetype)initPrivate {
self = [super init];
if (self) {
[self sessionConf];
NSURLSessionDataTask *getCategories =
[self.session dataTaskWithURL:categoriesURL
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
if (error) {
NSLog(@"error - %@",error.localizedDescription);
}
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *) response;
if (httpResp.statusCode == 200) {
NSError *jsonError;
NSArray *json =
[NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&jsonError];
if (!jsonError) {
_allCategories = json;
NSLog(@"allcategories - %@",_allCategories);
}
}
}];
[getCategories resume];
}
return self;
}
然后在 ViewController 我执行
- (void)fetchCategories {
NSLog(@"before");
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
CategoriesStore *categories = [CategoriesStore sharedStore];
dispatch_async(dispatch_get_main_queue(), ^(void) {
_allDirectories = categories.allCategories;
[self.tableView reloadData];
NSLog(@"after");
});
});
}
-fetchCategories 在 viewDidAppear 中执行。结果通常是之前,之后,然后是JSON。显然我想要得到的是before, json after。
我也尝试使用 dispatch_group_notify 来执行此操作,但没有成功。
我怎样才能让它工作?为什么它不等待第一个任务完成? 谢谢你的帮助! 问候,阿德里安。
【问题讨论】:
标签: ios objective-c json multithreading grand-central-dispatch