将通知观察器添加到自定义 class

Add notification observer to custom class

我是 Objective-C 的新手,我在添加通知观察器时遇到了问题。我有一个 class CoreDataStack,它是 NSObject 的子class。我正在尝试为 iCloud 同步添加通知观察器,但我不断收到编译器错误。代码感知在 NSNotificationCenter 上不可用。据我所知,我不需要导入任何额外的东西。我一定错过了一些非常明显的东西。

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

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

这是它给我的错误:

您的字符串 [[NSNotificationCenter defaultCenter] addObserver... 写得正确,但您必须将它放在某个方法中,而不是像现在这样放在顶层。

例如,这个方法可以放在你的 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");
}

当然任何其他 class 也可以工作,只需使该字符串 [[NSNotificationCenter defaultCenter] addObserver... 成为某些可执行方法的一部分。