【问题标题】:Core Location newLocation can't assign to property核心位置 newLocation 无法分配给属性
【发布时间】:2012-04-06 22:14:03
【问题描述】:

在 Apple 的文档中,他们展示了这种与 CoreLocation 一起使用来提取 GPS 数据的方法

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation     *)newLocation fromLocation:(CLLocation *)oldLocation 
{
}

这是为了通知您 GPS 已更新。 newLocation 将包含您需要的 GPS 数据,但如果我在此方法中添加一条语句以将其分配给一个属性,则会写入注释。

latitude = [NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];
NSLog(@"%@", latitude);

上面的 NSLog 放入方法中会显示正确的坐标。但是当方法结束时,数据似乎消失了。我班上的属性“纬度”没有被分配。也许这是一个范围问题?我无法从中返回任何内容,也无法在方法之外看到 newLocation。有没有人想办法解决这个问题?


编辑:我正在使用弧,纬度属性是强。我还需要其他属性吗? 这是我用来导入属性的实现代码。 (纬度是 LocationAwareness 的一个属性)这两个 nslog 都显示为空

#import "ViewController.h"
#import "LocationAwareness.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize location;

- (void)viewDidLoad
{
[super viewDidLoad];
self.location = [[LocationAwareness alloc] init];
NSLog(@"%@", location.latitude);
NSLog(@"%@", location.longitude);
}

【问题讨论】:

  • 如何声明纬度属性?
  • @property(strong) NSString *latitude;
  • 在这种情况下,使用 self.latitude 应该可以解决问题,正如我在回答中提到的那样。此外,除非您有非常具体的理由拒绝,否则您可能应该考虑将您的属性也声明为非原子的。
  • 你说纬度是LocationAwareness对象的一个​​属性,但你也有单独的纬度属性?
  • 另外,我没有看到你在合成你的纬度属性?

标签: iphone objective-c ios geolocation gps


【解决方案1】:

需要保留。不要忘记释放变量以再次使用,并在 dealloc 方法中。因此,您的 -didUpdateToLocation 方法应如下所示。

latitude = [[NSString stringWithFormat:@"%f", newLocation.coordinate.latitude] retain];

...

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation     *)newLocation fromLocation:(CLLocation *)oldLocation 
{
    if (latitude) {
        [latitude release];
    }

    latitude = [[NSString stringWithFormat:@"%f", newLocation.coordinate.latitude] retain];
}

否则,如果您使用 ARC,只需添加具有“强”属性的属性即可。

【讨论】:

    【解决方案2】:

    如果您使用 ARC 并且纬度是一个强属性,那么使用:

    self.latitude = [NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 2019-05-08
      相关资源
      最近更新 更多