@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,这才比较合理。