在GET函数体内能成功获取到正确数据,而函数外为null,我想应该是异步问题,那么,如何在函数(block)外面获取到正确的数据呢?
http://localhost/json/1.json 的内容如下:
{
"tempMinC": "11",
"tempMinF": "51",
"weatherCode": "113",
"winddirection": "WNW"
}
代码为:
#import "AFHTTPRequestOperationManager.h"
@interface ViewController ()
{
__block NSString *winddirection;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *url = @"http://localhost/json/1.json";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
winddirection = [(NSDictionary *)responseObject objectForKey:@"winddirection"];
NSLog(@"winddirection is %@",winddirection);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error...%@",error);
}];
NSLog(@"out of winddirection is %@",winddirection);
}
执行结果为:
2016-02-02 22:03:39.292 1[1042:60b] out of winddirection is (null)
2016-02-02 22:03:39.419 1[1042:60b] winddirection is WNW
如何在NSLog(@"out of winddirection is %@",winddirection);的地方获取到正确的数据呢?
根据你描述的貌似行不通,毕竟你是异步获取数据,获取完之后,不走你那个NSLog(@"out of winddirection is %@",winddirection);,你可以在block中获取到数据之后进行调用外部方法(在外部方法里面实现NSLog(@"out of winddirection is %@",winddirection);),进行赋值或者刷新UI。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。