【问题标题】:Access property before viewDidLoad在 viewDidLoad 之前访问属性
【发布时间】:2014-02-16 16:29:25
【问题描述】:

在下面的方法中,我保存了一个位置的当前临时值,我希望能够在类内的任何地方访问临时值。

[_weatherAPI currentWeatherByCoordinate:CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude) withCallback:^(NSError *error, NSDictionary *result) {
    downloadCount++;
    if (downloadCount > 1)
        if (error) {
        }
    [_locationManager stopUpdatingLocation];

    self.tempLabel.text = [NSString stringWithFormat:@"%.0f°",
                           [result[@"main"][@"temp"] floatValue] ];

    self.locationLabel.text = [NSString stringWithFormat:@"%@",
                               result[@"name"]
                               ];
    self.summaryLabel.text = [NSString stringWithFormat:@"%@",
                              result[@"weather"][0][@"main"] ];

    [self setSaveTemp:result[@"main"][@"temp"]];


}];

然后我将它保存到一个属性中

@property (strong, nonatomic) NSString *saveTemp;

然后将其保存到此。

-(void)setSaveTemp:(NSString *)saveTemp {
_saveTemp = saveTemp;
}

在我的 viewDidLoad 中,我正在调用所有内容

_weatherAPI = [[OWMWeatherAPI alloc] initWithAPIKey:@""];
[_weatherAPI setLangWithPreferedLanguage];
[_weatherAPI setTemperatureFormat:kOWMTempCelcius];

NSLog(@"%@", _saveTemp);

但这会返回 null,因为在 _weatherAPI currentWeatherByCoordinate 之前调用 viewDidLoad 我该怎么做才能使 _saveTemp 不等于 null 而是实际值?

【问题讨论】:

  • 时光机就足够了。
  • 对不起,我不明白?
  • 如果 _saveTemp 在 vi​​ewDidLoad 中没有准备好,你不能用它做任何事情。您必须更改应用程序逻辑。例如在其他地方处理 _saveTemp 以及何时准备好。例如你可以从_weatherAPI currentWeatherByCoordinate调用一些[self displayTempMethod]@

标签: ios objective-c


【解决方案1】:

我认为这个 api 会调用服务器,因此获取 json 数据需要时间。 一旦json数据可用,就会执行回调块。

saveTemp 变量最初将是nil,您将其设置在完成块中。

你所能做的就是等到下载完成。如果你想在下载后执行某个方法,那么在callBack块中调用那个方法。这样,您的应用就可以知道下载已完成。

【讨论】:

    猜你喜欢
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多