macos - 观察NSArrayController的变化: detect insertion or deletion

标签 macos cocoa core-data cocoa-bindings nsarraycontroller

我有一个 NSArrayController,它绑定(bind)到我的核心数据模型中的实体“Address”。我想监视哪些新对象被插入到此地址实体中,或者哪些现有对象被删除。我正在尝试通过 KVO 来做到这一点,但我不确定应该如何去做。

在我的 awakeFromNib 中,我添加 View Controller 类作为“arrangedObjects”的观察者:

[self.addressArrayController addObserver:self
                                    forKeyPath:@"arrangedObjects"
                                       options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
                                       context:@"Address"];

我确实收到了观察者通知:

- (void)observeValueForKeyPath:(NSString *)keyPath
                  ofObject:(id)object
                    change:(NSDictionary *)change
                   context:(void *)context {

   if( object == self.addressArrayController) {
      // what do do here?
   }
}

问题是更改字典总是为零(我相信是由于一些长期存在的Apple bug),所以我不知道添加或删除了哪个对象,甚至不知道添加或删除了某些内容!而且我确实需要添加或删除的确切对象,理想情况下无需遍历该实体的所有对象并尝试根据对象的时间戳或任何其他标准来找出。

最好的方法是什么?

最佳答案

改编自my answer here ,其中列出了 gaige 在评论中建议的代码。

注册 NSManagedObjectContextObjectsDidChangeNotification:

[[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(mocDidChangeNotification:)
                              name:NSManagedObjectContextObjectsDidChangeNotification
                                           object: nil];

并在相应的方法中解析userInfo字典:

- (void)mocDidChangeNotification:(NSNotification *)notification
{
    NSManagedObjectContext* savedContext = [notification object];

    // Ignore change notifications for anything but the mainQueue MOC
    if (savedContext != self.managedObjectContext) {
        return;
    }

    // Ignore updates -- lots of noise from maintaining user-irrelevant data

    // Log insertion
    for (NSManagedObject* insertedObject in 
           [notification.userInfo valueForKeyPath:NSInsertedObjectsKey])
    {
        if ([insertedObject isKindOfClass:[Address class]] )
        {
            NSLog(@"Inserted Address");
        }
    }   

    // Log deletion
    for (NSManagedObject* deletedObject in 
           [notification.userInfo valueForKeyPath:NSDeletedObjectsKey])
    {
        if ([deletedObject isKindOfClass:[Address class]] )
        {
            NSLog(@"Deleted Address");
        }
    }

}

关于macos - 观察NSArrayController的变化: detect insertion or deletion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23823232/

相关文章:

swift - 如何设置 Cocoa 应用程序标题栏的样式?

objective-c - 颜色菜单选择器

ios - 核心数据 : how to just delete and rebuild the data store?

ios - 识别 iCloud coreData 更新 : good practice

objective-c - 如何将 NSLayoutConstraint 添加到以编程方式创建的 NSView 子类的 subview 中?

xcode - 如何知道应用程序是否首次在 Mac 上运行

macos - SwiftUI:如何从 macOS 上的“通讯录”中拖放联系人

ios - 如何通过按钮更新分配给自定义单元格中索引路径的核心数据

ios - NSUserDefaults 和查询在 Mavericks Mac OSX 10.9 中不起作用

mysql - 将 Mac 上的 MAMP 链接到 MySQL 和 phpMyAdmin 的不同实例