1

我正在使用 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........

我已经尝试了很多与范围界定相关的项目,显然只是错过了标记。有任何想法吗?我已经搜索了设置全局变量等。现在一直停留在这个问题上。

谢谢,

瑞安

4

2 回答 2

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 = ...当您进行分配时,将从异步代码中调用此方法。

于 2013-12-19T03:21:32.263 回答
0

尝试在主线程上设置对象:

    [self performSelectorOnMainThread:@selector(setTideData:) withObject:[NSJSONSerialization JSONObjectWithData:self.rawResults options: 0 error: &error] waitUntilDone:NO];


- (void)setTideData:(NSDictionary*)dict {
self.tideData = dict;
}
于 2013-12-19T10:28:58.253 回答