Objective c NSKEYVALUE不工作
我编写了一个名为LocationManager的CLLocationManager单例,希望观察更新的位置。但观察部分不起作用。谁能告诉我是什么问题吗。谢谢以下是我的代码:Objective c NSKEYVALUE不工作,objective-c,cllocationmanager,nskeyvaluecoding,Objective C,Cllocationmanager,Nskeyvaluecoding,我编写了一个名为LocationManager的CLLocationManager单例,希望观察更新的位置。但观察部分不起作用。谁能告诉我是什么问题吗。谢谢以下是我的代码: -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ if(object == self){ if([keyPath is
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if(object == self){
if([keyPath isEqualToString:@"curStandardLocation"]){
NSLog(@"current location is changed ....");
}
}}(in LocationManager.m)
if([self.locationManager locationmanagerstatus]){
[self.locationManager startLocationTracking];
[[LocationManager sharedInstance] addObserver:self forKeyPath:@"curStandardLocation" options:NSKeyValueObservingOptionNew context:nil];} (in a separate viewcontroller where I need to listen to the location)
如果要跟踪位置更改,可以使用 在控制器的
init
方法中实例化管理器:
_locationManager = [[CLLocationManager alloc] init];
[_locationManager setDelegate:self];
[_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
[locationManager requestWhenInUseAuthorization];
}
在视图中将出现:
方法中,开始监视意义位置的更改
if ([CLLocationManager locationServicesEnabled]) {
// Find the current location
[self.locationManager startMonitoringSignificantLocationChanges];
//rest of code...
}
重大变化监控很好,因为:
- 它比更频繁的更新类型具有更低的功耗李>
- “重大”变化是可变的,但远小于触发推力的几英里
- 即使应用程序在后台,也会调用代理,允许使用以持续更新用户的位置,即使不使用应用程序
locationManager:didUpdateLocations:
和locationManager:didFailWithError:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
// locations contains an array of recent locations, but this app only cares about the most recent
// which is also "manager.location"
}
同时添加您的info.plist
<key>NSLocationUsageDescription</key>
<string>The application require location services to work</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>The application require location services to work</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>The application require location services to work</string>
NSLocationUsageDescription
应用程序需要位置服务才能工作
N位置始终使用说明
应用程序需要位置服务才能工作
NSLocationWhenUse用途说明
应用程序需要位置服务才能工作
从您描述它的方式来看,它不像observeValueForKeyPath
在添加自身作为观察者的同一个对象中。Phillip的评论为+1,另外:添加键值观察者时,您应该始终使用唯一的上下文。您应该始终检查-observeValueForKeyPath:…
中的上下文,如果它与您的上下文不匹配,则调用super。-observeValueForKeyPath:…
中的对象
参数是观察到的对象,其属性正在更改。它通常不是self
。在您的情况下,它将是[LocationManager sharedInstance]
。最后,您需要注意确保您的LocationManager
类的cursorstandardLocation
属性符合KVO。@PhillipMills感谢您的帮助。你能详细说明你的答案吗?我不明白(@Kenthomass非常感谢您的帮助。我应该对CursStandardLocation属性设置什么样的约束?您只需要以生成KVO更改通知的方式对其进行操作。这主要意味着您必须始终通过其setter进行设置,决不能直接将其分配给实例变量。请参阅。