我试图发送位置更新与新位置作为通知对象。当我这样做时,当我尝试访问通知中的数据时,会收到“EXC_BAD_ACCESS”错误。如果我执行“po location”,我会看到数据,但是我不清楚为什么我无法获取它。设置观察者时,我也尝试将对象参数分配给成员变量,但是不会调用locationUpdate。如何从NSNotification对象获取数据?
这里是我的代码(注意,ARC已启用):
// LocationController.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
// LocationController.m
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[Notification locationChanged:newLocation];
}
// Notification.h
@interface Notification : NSObject
+ (void)locationChanged:(CLLocation *)newLocation;
@end
extern NSString *const kLocationChanged;
// Notification.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);
LOL。我有%f开始,但是我还有其他缺陷,并且正在上课。修复了一些其他缺陷后,我忘了将它改回来。我曾假设我没有解决我原来的问题。感谢您的发现:) – TERACytE 2012-02-12 18:16:42
没问题。有时候,我们错过了小事。 – cocoakomali 2012-02-13 20:44:52