我試圖發送位置更新與新位置作爲通知對象。當我這樣做時,當我嘗試訪問通知中的數據時,會收到「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