【问题标题】:Variable goes null in other function in objective-c变量在objective-c的其他函数中变为空
【发布时间】:2013-02-28 09:02:41
【问题描述】:

我的 ViewController 中有两个变量。在我的.h 中,我是这样定义它们的。

@property (nonatomic, strong) NSString *myLongitude;
@property (nonatomic, strong) NSString *myLatitude;

在我的.m 中,我已经合成了它们。像这样。

@synthesize myLatitude = _myLatitude;
@synthesize myLongitude = _myLongitude;

然后在函数updateLocation 中设置这些变量如下。

 _myLongitude = [[NSString alloc]initWithFormat:@"%f",location.longitude];
   _myLatitude = [[NSString alloc]initWithFormat:@"%f",location.latitude];

当我在设置这些变量之后记录这些变量时,我会得到正确的值。但是,当我在更新函数之后执行的另一个函数中记录值时,这些变量会变为NULL。这是我的日志。

        NSLog(@"longitude val is = %@", _myLongitude);
        NSLog(@"latitude val is = %@", _myLatitude);

有什么帮助吗?

【问题讨论】:

  • 如果你使用 ARC,那么你不需要像@synthesize myLatitude = _myLatitude; 那样进行合成,@synthesize myLatitude; 就足够了,因为你的位置也可以是 null
  • 是的,我使用 ARC。这可能是问题吗?
  • 首先检查你的 location.lon/lat 不为空,把 NSLog 转换成字符串 :)
  • 尝试一次,对这些变量使用 setter,而不是使用 _myLongitude 或 _myLatitude。
  • 在将它们传递给 google API 之前将它们转换为字符串。

标签: iphone ios objective-c nsstring


【解决方案1】:

然后在函数 updateLocation 我将这些变量设置为 关注。

显然这些是类的属性,updateLocation 不是 allocate 和 initialise 的正确位置。

您应该使用viewDidLoadinit 或类似的方法进行操作。

如果您想重新设置该值,请将其设置为nil,然后输入新值而不是这样做。

【讨论】:

  • 所以我只是在 ViewDidLoad 中 [[alloc]init] 它们并在 updateFunction 中设置它们?
  • 我试过了,但没有成功。继续为空。我在 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 函数中设置了我的变量。
  • 对象location 怎么样,它必须被释放,导致_myLatitude_myLongitude 为空。是强类型吗?
  • 是的,它们属于强类型。
  • 您是否正在创建不同的location 实例?否则我根本看不到任何问题:(
猜你喜欢
  • 2012-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 2020-03-22
  • 1970-01-01
相关资源
最近更新 更多