0

我尝试使用我的 locationManager 实现以下功能:

开始更新用户位置

- (void)startStandardUpdates {
    if (self.locationManager == nil) {
        self.locationManager = [[CLLocationManager alloc] init];
    }

    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    // Set a movement threshold for new events
    self.locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters;

    [self.locationManager startUpdatingLocation];

    CLLocation *currentLocation = self.locationManager.location;

    if (currentLocation) {
        self.currentLocation = currentLocation;
    }
}

为我的属性实现自定义设置以发送通知

- (void)setCurrentLocation:(CLLocation *)currentLocation {
    self.currentLocation = currentLocation;
    NSLog(@"%f", currentLocation.coordinate.latitude);

    //Notify the app of the location change
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:self.currentLocation forKey:kIFLocationKey];
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:kIFLocationChangeNotification object:nil userInfo:userInfo];
    });
}

问题是:当我运行应用程序时,在调试模式下的“setCurrentLocation”方法中收到“BAD_EXEC(代码 2)”错误消息,应用程序已挂起。但我不明白这个问题。我错过了什么吗?据我所知,在“startStandardUpdates”中,如果位置管理器找到了用户的位置,则使用我的自定义设置器“self.currentLocation = currentLocation”更新属性“currentLocation”。

提前感谢您的帮助!关于塞巴斯蒂安

4

1 回答 1

2

您实现 setter 的方式是问题所在。self.currentLocation = ... 导致 setter 被调用,并且您在实现 setter 时调用它,这会导致无限循环。如下合成您的 ivar,并仅在 setter(和 getter)中使用 _variablename。

@synthesize currentLocation = _currentLocation;

//二传手

- (void)setCurrentLocation:(CLLocation *)currentLocation {
    _currentLocation = currentLocation;
    NSLog(@"%f", currentLocation.coordinate.latitude);

    //Notify the app of the location change
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:self.currentLocation forKey:kIFLocationKey];
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:kIFLocationChangeNotification object:nil userInfo:userInfo];
    });
}
于 2013-02-09T10:31:34.950 回答