我正在尝试以新位置作为通知对象发送位置更新。当我这样做时,当我尝试从通知中访问数据时收到“EXC_BAD_ACCESS”错误。如果我执行“po location”,我会看到数据,但我不清楚为什么我无法获取它。设置观察者时,我也尝试将对象参数分配给成员变量,但从未调用 locationUpdate。
这是我的代码(请注意启用了 ARC):
// 位置控制器.h
@protocol LocationDelegateProtocol
@required
- (void)locationUpdate:(CLLocation *)location;
@end
@interface LocationController : NSObject <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
id delegate;
}
@property(nonatomic, retain) CLLocationManager *locationManager;
@property(nonatomic, strong) id delegate;
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation;
+ (LocationController *)sharedInstance; // this class is a singleton
@end
// 位置控制器.m
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[Notification locationChanged:newLocation];
}
// 通知.h
@interface Notification : NSObject
+ (void)locationChanged:(CLLocation *)newLocation;
@end
extern NSString *const kLocationChanged;
// 通知.m
NSString *const kLocationChanged = @"NewLocation";
[[NSNotificationCenter defaultCenter] postNotificationName:kLocationChanged object:newLocation];
// ViewController.h
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, LocationDelegateProtocol> {
...
}
...
- (void)locationUpdate:(CLLocation *)location;
@end
// ViewController.m
- (void)setupNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(locationUpdate:) name:kLocationChanged object:nil];
// I've tried setting object to a member var "CLLocation *objectFromNotification", but then locationUpdate() is never called.
}
- (void)locationUpdate:(NSNotification *)notification {
CLLocation *location = (CLLocation *) [notification object];
// program receives signal "EXC_BAD_ACCESS" when executing NSLog below. I can see data inside location when I execute "po location".
NSLog(@"latitude = %@, longitude = %@",location.coordinate.latitude, location.coordinate.longitude);