【发布时间】:2016-03-29 08:37:55
【问题描述】:
我有一个NSManagedObjectContextObjectsDidChangeNotification 的问题,在插入对象然后执行回滚(因此它被删除)之后,关于删除的更改通知被调用了两次。这个意外的通知给我带来了麻烦,我已经追溯到这个问题。我编辑了Apple's Earthquakes example 来演示这个问题。编辑是:
- (void)viewDidLoad {
[super viewDidLoad];
[self reloadTableView:self];
[NSNotificationCenter.defaultCenter
addObserver:self
selector:@selector(contextObjectsDidChangeNotification:)
name:NSManagedObjectContextObjectsDidChangeNotification
object:self.managedObjectContext];
AAPLQuake* quake = (AAPLQuake *)[NSEntityDescription insertNewObjectForEntityForName:@"Quake" inManagedObjectContext:self.managedObjectContext];
NSLog(@"Why is deleted notified twice?");
[self.managedObjectContext rollback];
}
- (void)contextObjectsDidChangeNotification:(NSNotification *)notify{
NSLog(@"contextObjectsDidChangeNotification:");
NSDictionary* userInfo = notify.userInfo;
NSSet* inserted = userInfo[NSInsertedObjectsKey];
if(inserted){
NSLog(@"\tinserted %ld", inserted.count);
}
NSSet *deleted = userInfo[NSDeletedObjectsKey];
if(deleted){
NSLog(@"\tdeleted %ld", deleted.count);
}
}
运行它会产生以下输出:
2015-12-23 00:15:20.086 Earthquakes[7631:5431685] Why is deleted called twice?
2015-12-23 00:15:20.086 Earthquakes[7631:5431685] contextObjectsDidChangeNotification:
2015-12-23 00:15:20.086 Earthquakes[7631:5431685] inserted 1
2015-12-23 00:15:20.086 Earthquakes[7631:5431685] contextObjectsDidChangeNotification:
2015-12-23 00:15:20.087 Earthquakes[7631:5431685] deleted 1
2015-12-23 00:15:20.087 Earthquakes[7631:5431685] contextObjectsDidChangeNotification:
2015-12-23 00:15:20.087 Earthquakes[7631:5431685] deleted 1
提供示例项目here。
有人知道为什么会这样吗?我在 OS X 10.11.2 和 iOS 9.2 上都体验过。
【问题讨论】:
-
你在哪里删除了观察者?
-
我可以确认我看到了相同的行为,但不确定是什么原因。
-
感谢您确认您看到了相同的行为。我尝试使用撤消管理器而不是回滚,它没有这个问题。
标签: ios objective-c macos core-data rollback