我正在开发一个iPhone应用程序,需要用户指定的时间间隔进行位置更新。下面是代码示例,我用它来做这件事:
@implementation TestLocation
- (void)viewDidLoad{
if ([Utils getDataWithKey:TIMER_INTERVAL] == nil) {
[Utils saveDataWithKey:TIMER_INTERVAL withValue:@"60.0"];
}
locationManager = [[[CLLocationManager alloc] init] autorelease];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
- (void)startLocationManager:(NSTimer *)timer{
[locationManager startUpdatingLocation];
[timer invalidate];
timer = nil;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
// Here is code to handle location updates...
[manager stopUpdatingLocation];
// Timer will start getting updated location.
NSTimeInterval timeInterval = [[Utils getDataWithKey:TIMER_INTERVAL] doubleValue];
[NSTimer scheduledTimerWithTimeInterval:timeInterval
target:self
selector:@selector(startLocationManager:)
userInfo:nil
repeats:NO];
}
// other implementations ...
@end
代码运行得很好。
问题是:
我使用CLLocationManager
和NSTimer
,这会影响内存或电池消耗吗?我的意思是对用户体验有负面影响吗?
如果是这样,任何建议,帮助链接做这样的任务优化将不胜感激。
注: Utils
是我的类存储或检索数据
是的,这将有一些副作用,您将无法获得所需的准确性。因为每次GPS信号都会调用locationManager:didUpdateToLocation:fromLocation:
这不是一个好策略,因为您可以在第一次调用[manager stopUpdatingLocation]
之前接收多个异步位置事件。这将导致创建指数数量的计时器。
相反,只需在创建位置管理器后启动重复计时器,并在每次接收到事件后仍然停止位置管理器。