在苹果的文档中,他们展示了与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);
}
它需要保留。不要忘记释放变量以供再次使用,并在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,只需添加一个具有"strong"属性的属性。
如果您正在使用ARC,并且纬度是一个强属性,则使用:
self.latitude = [NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];