我正在使用UNIRest进行调用并将JSON对象返回给我的应用程序。我把它作为NSDictionary返回正确的数据,它记录了我们的完美。我现在正在尝试获取该数据并将其显示在我的视图中。我不能在回调之外使用我的字典。
我一直在StackOverflow上挖掘类似的结果以及与变量相关的帖子。我认为这是一个范围问题,它仅限于回调块内部。
我的头文件:(UIViewController)
@property(nonatomic,strong)NSDictionary * tideData;
我的实施:
@interface TideDetailViewController ()
@end
@implementation TideDetailViewController
@synthesize tideData;
- (void)viewDidLoad {
[super viewDidLoad];
// tideData = [[NSDictionary alloc] init];
// location is working, I removed it for testing to call a static string for now
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[self.locationManager startUpdatingLocation];
NSString *locationQueryURL = @"http://api.wunderground.com/api/XXXXXXXXXXXXX/tide/geolookup/q/43.5263,-70.4975.json";
NSLog(@"%@", locationQueryURL);
[[UNIRest get:^(UNISimpleRequest *request) {
[request setUrl: locationQueryURL];
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
// This is the asyncronous callback block
self.code = [response code];
NSDictionary *responseHeaders = [response headers];
UNIJsonNode *body = [response body];
self.rawResults = [response rawBody];
// I tried this as self as well
tideData = [NSJSONSerialization JSONObjectWithData:self.rawResults options: 0 error: &error];
// this logs perfectly.
NSLog(@"tideData %@", tideData);
// tried setting it to the instance
//self.tideData = tideData;
}];
// returns null
NSLog(@"tideData outside of call back %@", self.tideData);
// this is where I will be setting label text for now, will refactor once I get it working
// rest of file contents........
我尝试了大量与范围有关的项目,显然只是错过了标记。有任何想法吗?我已经搜索了设置全局变量等等。现在已经坚持了一下。
谢谢,
赖安
答案 0 :(得分:0)
您看到nil
的原因是因为您过早登录:当您致电
NSLog(@"tideData outside of call back %@", self.tideData);
get:asJsonAsync:
方法尚未收到结果。
您可以通过为您的媒体资源添加setter并为其添加一些特殊处理来解决此问题,例如:
-(void)setTideData:(NSDictionary*)dict {
_tideData = dict;
NSLog(@"tideData outside of call back %@", _tideData);
}
执行tideData = ...
赋值时,将从异步代码调用此方法。
答案 1 :(得分:0)
尝试在主线程上设置对象:
[self performSelectorOnMainThread:@selector(setTideData:) withObject:[NSJSONSerialization JSONObjectWithData:self.rawResults options: 0 error: &error] waitUntilDone:NO];
- (void)setTideData:(NSDictionary*)dict {
self.tideData = dict;
}