學習AFnetworking時遇到數據的獲取問題:
在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。