无法使用自定义setter设置属性

时间:2013-02-09 10:27:11

标签: iphone properties location core-location

我尝试使用我的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”中,如果位置管理器找到了用户的位置,则使用我的自定义setter“self.currentLocation = currentLocation”更新属性“currentLocation”。

提前感谢您的帮助! 问候 塞巴斯蒂安

1 个答案:

答案 0 :(得分: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];
    });
}