iphoneobjective-cxcodeipadnsnotification

How do I acquire data from a NSNotification object?


I am trying to send a location update with the new location as a notification object. When I do, I receive a "EXC_BAD_ACCESS" error when I try to access the data from the notification. If I execute "po location" I see the data, but it is unclear to me why I cannot acquire it. When setting the observer, I also tried assigning the object parameter to a member variable, but then locationUpdate is never called.

Here's my code (note that ARC is enabled):

// 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); 

Solution

  • Change the format specifier in your NSLog from %@ to %f. You are trying to access float value as object!