gpt4 book ai didi

ios - CoreData NSUndoManager 关系问题

转载 作者:行者123 更新时间:2023-12-01 16:29:35 28 4
gpt4 key购买 nike

我有一个与部门具有多对一关系的托管对象 Employee。因此,一个员工可以在一个部门中,但部门可以包含多个员工。

我使用撤消管理器来注册某些员工的删除。之后我关闭撤消注册我删除部门。部门删除会删除所有剩余的员工,因为它有 Cascade Delete规则就可以了。

NSManagedObjectContext *defaultContext = [NSManagedObjectContext MR_defaultContext];        
NSUndoManager *undoManager = [defaultContext undoManager];

[undoManager enableUndoRegistration];
[undoManager setActionName:@"Delete"];

[employee MR_deleteEntityInContext:defaultContext];

// let undo manager finish registering events on current run loop
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate date]];
[undoManager disableUndoRegistration];

// ...

// somewhere later without undo manager enabled
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
Department *department = [departmentOnMainThread MR_inContext:localContext];
[department MR_deleteEntityInContext:localContext];
}];

然后我撤消删除 Employee ,它在我的上下文中与 Department 一起复活。
NSManagedObjectContext *defaultContext = [NSManagedObjectContext MR_defaultContext];        
NSUndoManager *undoManager = [defaultContext undoManager];

[undoManager enableUndoRegistration];
[undoManager undo];

[defaultContext MR_saveToPersistentStoreAndWait];

// let undo manager finish registering events on current run loop
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate date]];
[undoManager disableUndoRegistration];

有趣的是,当我运行 undo 时, [defaultContext deletedObjects]我的上下文包含我最初使用 NSUndoManager 捕获的部门、员工以及其他一些可能与 Department 一起被删除的 Employee ,但在删除原始 Employee 期间实际上并未捕获该更改。这个其他 Employee 的所有字段都设置为 nil。

出于好奇,我调用 [defaultContext refreshAllObjects]回应:

CoreData: warning: An NSManagedObjectContext delegate overrode fault handling behavior to silently delete the object with ID '0xd000000000280000 ' and substitute nil/0 for all property values instead of throwing.



问题是,可能其他 Employee 应该真的被删除了,但是我怎样才能恢复原来的 Employee 和 Department ,这两个显然都应该放回数据库?
NSUndoManager将它们恢复为已删除的对象,这没有多大意义。

最佳答案

Amin Negm-Awad 所述:

You cannot undo an action, that has a subsequent action. Undoing the forecast action is impossible in many cases and of course not supported. (I. e. undoing the deletion of the employees cannot bring back the department they belong to.) You have to register all actions or none, otherwise you fight the framework. It's is still a stack and it will be a stack when I write my next comment. Therefore obviously you cannot select operations for undoing and operations not for undoing. So register all actions and use undo groups.

关于ios - CoreData NSUndoManager 关系问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32553517/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com