我需要使用 CLLocation
我需要从 GPS 读取我的位置! 问题是我需要从方法中完成
- (void)locationUpdate:(CLLocation *)location;
所以...这就是我的工作方式:
在 .h 文件中,我
CLLocation *mylocation;
在 -viewDidLoad 中
mylocation = [[CLLocation alloc] init];
locationController = [[CLController alloc] init];
locationController.delegate = self;
[locationController.locationManager startUpdatingLocation];
有这个,然后
- (void)locationUpdate:(CLLocation *)location {
mylocation = location;
}
它可以工作,如果我使用 NSLog (在我的位置上)我查看我的真实位置! 但是...在另一种方法(与 UIButton 连接的 IBAction)中,我想使用“mylocation”! 它不起作用,我不知道为什么!
如果在这种方法中,我尝试执行此操作,
NSLog(@"%@", mylocation);
控制台会报告以下内容:
<+0.00000000, +0.00000000> +/- 0.00m (speed -1.00 mps / course -1.00) @ 3/10/11 7:21:24 PM Central European Time
所以变量为空!
为什么??
PS= 当然,我的 IBAction 中也有,否则
mylocation = [[LCLocation alloc] init];
应用程序会崩溃!
I need to read my position from GPS!
The problem is that i need to do out from the method
- (void)locationUpdate:(CLLocation *)location;
So... this is how i'm working:
in the .h file i have this
CLLocation *mylocation;
in the -viewDidLoad
mylocation = [[CLLocation alloc] init];
locationController = [[CLController alloc] init];
locationController.delegate = self;
[locationController.locationManager startUpdatingLocation];
then
- (void)locationUpdate:(CLLocation *)location {
mylocation = location;
}
and it works, if i use NSLog (on mylocation) i see my real location!
But... in another method (an IBAction connected with a UIButton) i want to use "mylocation"!
It's not working and i don't know why!
If, in this method, i try to do this
NSLog(@"%@", mylocation);
the console report this:
<+0.00000000, +0.00000000> +/- 0.00m (speed -1.00 mps / course -1.00) @ 3/10/11 7:21:24 PM Central European Time
So the variable is empty!
Why??
PS= also in my IBAction i have, of course, this
mylocation = [[LCLocation alloc] init];
otherwise the app crashes!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这一行:
将 mylocation 的内存指针设置为位置管理器返回的内存指针,该指针稍后将被释放。
编辑:
This line:
Is setting mylocation's memory pointer to the one returned by the location manager, which later is getting released.
EDITED:
所以你得到零值,因为你总是用新创建的空白位置覆盖你的位置值 - 你不应该这样做。
导致应用程序崩溃的问题是,在
locationUpdate
方法中,您获得自动释放的值,因此为了确保其在该方法之外有效,您必须保留它。 (并且不要忘记释放旧值)。最简单的方法是创建一个 属性< /a> 为 myLocation ivar 并使用它访问 ivar:So you get zero values because you always overwrite your location value with newly created blank location - you should not do that.
The problem that makes your application crash is that in
locationUpdate
method you get autoreleased value, so in order to ensure that its valid outside of that method you must retain it. (and not forget to release old value). The easiest way to do that is create a property for myLocation ivar and access ivar using it: