@property (nonatomic, strong) NSDictionary *dic;
#pragma mark - 從網絡獲取json數據
(NSDictionary *)getJsonData{
NSString *urlStr = @"http://api.worldweatheronline.com/free/v2/weather.ashx?q=chengdu&num_of_days=7&format=json&tp=6&key=5fc3a5873e9bdb5bbf8116ea3aac5";
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//使用AFNetworking解析json數據
//實例化http操作請求
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//設定解析器
operation.responseSerializer = [AFJSONResponseSerializer serializer];
//下載數據並解析
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//json數據全局化
self.dic = (NSDictionary *)responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"解析出錯:%@",error);
}];
});
[operation start];
return self.dic;
}
我已經提升dic成屬性了,為什麼返回的self.dic為空?
個人猜想是跟 block 執行時期有關,希望能有人指點迷津,謝謝!
你這是創建一個分線程去下載數據,但是下載完成後沒有刷新主線程。你這邊返回的self.dic是肯定是空得。應該是下載完成(下載成功或者失敗都是完成)後再返回dic,這才比較合理。