【问题标题】:Can't set property with custom setter无法使用自定义设置器设置属性
【发布时间】:2013-01-25 01:53:01
【问题描述】:

我尝试使用我的 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”。

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

【问题讨论】:

    标签: iphone properties location core-location


    【解决方案1】:

    您实现 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];
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-17
      • 1970-01-01
      • 2022-10-30
      • 2023-02-10
      • 2021-11-29
      • 1970-01-01
      • 2012-07-02
      • 2022-11-19
      相关资源
      最近更新 更多