Search code examples
objective-cios9

Add notification observer to custom class


I am new to Objective-C and I’m having trouble adding a notification observer. I have a class CoreDataStack that’s a subclass of NSObject. I am trying to add notification observers for iCloud sync but I keep getting compiler errors. Code sense is not picking up on NSNotificationCenter. As far as I know there isn’t anything extra I need to import. I must be missing something really obvious.

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(persistentStoreCoordinatorStoresDidChange:)
                                             name:NSPersistentStoreCoordinatorStoresDidChangeNotification
                                           object:self.persistentStoreCoordinator];

- (void)persistentStoreCoordinatorStoresDidChange:(NSNotification*)notification {
    NSLog(@"persistentStoreDidImportUbiquitousContentChanges");
}

Here are the errors it's giving me:

  • Missing '[' at start of message send expression
  • Use of undeclared identifier 'self'
  • Expected identifier or '('

Solution

  • Your string [[NSNotificationCenter defaultCenter] addObserver... is written correctly but you have to put it inside some method, not to the top level as it is now.

    For example this method can be put inside your AppDelegate:

    #import <CoreData/CoreData.h>
    
    @interface AppDelegate ()
    
    @property (nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
    ...
    @end
    
    @implementation AppDelegate
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        // Initialize self.persistentStoreCoordinator somehow....
        // ...
    
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(persistentStoreCoordinatorStoresDidChange:)
                                                     name:NSPersistentStoreCoordinatorStoresDidChangeNotification
                                                   object:self.persistentStoreCoordinator];
    
        return YES;
    }
    
    - (void)persistentStoreCoordinatorStoresDidChange:(NSNotification*)notification {
        NSLog(@"persistentStoreDidImportUbiquitousContentChanges");
    }
    

    Of course any other class will also work, just make that string [[NSNotificationCenter defaultCenter] addObserver... to be a part of some executable method.