最近我開始爲iOS開發,面臨的問題可能很明顯,但我自己無法弄清楚。 我想要做的是使用GCD提供的多線程來執行另一個任務。接下來執行任務
這是我取的JSON代碼(放在類單) CategoriesStore
- (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;
}
然後在視圖控制器我執行
- (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。顯然我想得到的是之前,json在之後。
我也試着用dispatch_group_notify做到這一點,但沒有工作。
我該如何得到它的工作?爲什麼它不等待第一項任務完成? 感謝您的幫助! 問候,阿德里安。