我编写了以下代码来查找当前位置。
当我在lat2
下面打印logg2
和NSLOg
时,它运行良好并打印当前位置,但它没有为标签赋值。当我打印label时,该值为null。
我想访问方法didUpdateToLocation之外的lat2和logg2值。 尽管如此,我无法在didUpdateToLocation方法之外访问这些值 我已经全局声明了logg2和lat2。在此方法之外,它给出null值。我怎样才能做到这一点?这有什么问题?是否有任何示例代码或教程?
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
-(void)awakeFromNib {
[self update];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (wasFound) return;
wasFound = YES;
CLLocationCoordinate2D loc = [newLocation coordinate];
lat2 = [NSString stringWithFormat: @"%f", loc.latitude];
logg2= [NSString stringWithFormat: @"%f", loc.longitude];
NSLog(@"latitude is %@",lat2);
NSLog(@"longitude is %@",logg2);
NSLog(@"*******This is the login view controller did update locationmethod of loginview controller.");
NSLog(@"latitude is %f",[lat2 floatValue]);
NSLog(@"longitude is %f",[logg2 floatValue]);
labellat.text = [NSString stringWithFormat: @"%f", loc.latitude];
labellog.text= [NSString stringWithFormat: @"%f", loc.longitude];
//NSLog(@"text of label is %@",labellat.text);
//NSLog(@"text of label is %@",labellog.text);
//lat=loc.latitude;
//log=loc.longitude;
//altitude.text = [NSString stringWithFormat: @"%f", newLocation.altitude];
// NSString *mapUrl = [NSString stringWithFormat: @"http://maps.google.com/maps?q=%f,%f", loc.latitude, loc.longitude];
// NSURL *url = [NSURL URLWithString:mapUrl];
// [[UIApplication sharedApplication] openURL:url];
}
- (IBAction)update {
locmanager = [[CLLocationManager alloc] init];
[locmanager setDelegate:self];
[locmanager setDesiredAccuracy:kCLLocationAccuracyBest];
NSLog(@"*********This is the location update method of login view controller.");
[locmanager startUpdatingLocation];
}
答案 0 :(得分:1)
基本内存管理:
lat2 = [NSString stringWithFormat: @"%f", loc.latitude];
logg2= [NSString stringWithFormat: @"%f", loc.longitude];
这些字符串在创建后几乎就被销毁(解除分配)。阅读内存管理指南。不要使用全局变量。如果必须,这应该可以解决你的字符串消失的问题:
[lat2 release];
[logg2 release];
lat2 = [[NSString stringWithFormat: @"%f", loc.latitude] retain]; // keep string alive until we release it
logg2= [[NSString stringWithFormat: @"%f", loc.longitude] retain];
哦,你还记得在Interface Builder中将插座连接到你的标签吗?
答案 1 :(得分:0)
您可以使用
labellat.text = [NSString stringWithFormat: @"%@", lat2];
labellog.text= [NSString stringWithFormat: @"%@", logg2];
但我认为最好将纬度和经度值作为浮动本身存储在实例变量中,从而轻松访问它。如果您想在标签中显示它,请使用方法stringWithFormat:
,就像您一样。
<强>更新强>
教程 Hello There: A CoreLocation Tutorial 可以为您提供帮助。
答案 2 :(得分:0)
用此标签显示标签中的纬度和经度。
labellat.text = [NSString stringWithFormat: @"%.6f", loc.latitude];
labellog.text= [NSString stringWithFormat: @"%.6f", loc.longitude];
如果你想从任何其他地方调用这个值,请保留位置坐标以获取值,否则它可能是autorelase。