iphone - 当线程在保存时被杀死时,如何防止 NSManagedObjectContext 破坏数据库?

标签 iphone ios core-data concurrency nsmanagedobjectcontext

In this question, octy wrote :

BTW, if you save on a background thread, you also need to consider what happens when your app is terminated while a save operation is in progress. Background threads get killed right away, whereas the watchdog waits 5 seconds for the main thread to finish up.

现在我花了一整天的时间来实现 NSOperation 并直接在 NSOperation 子类中创建 NSManagedObjectContext 实例,因此每个 NSOperation 都拥有自己的非共享 MOC。但现在这是一个非常坏的消息,因为这种情况很可能一直发生,会破坏 Core Data 数据库。我的意思是它不能开始在 sqlite3 文件中写入半字节的内容然后立即停止。

然后还有另一个问题:在我的 NSOperations 中,我还使用 NSFileManager 进行文件 I/O。

那我该怎么办呢?我必须跟踪我的应用程序中所有正在运行的 NSOperations 和 NSOperationQueues 并在应用程序终止时在 App Delegate 中快速处理它们,以便我可以告诉 NSOperations 到 SFF(Save F*****g Fast)或取消所有操作,捕获他们的 MOC 并立即“硬保存”他们?解决此问题的最佳做法是什么?

为什么我在我的职业生涯中第一次听说这个?我的意思是 NSOperationQueue 和 Core Data 提到的书籍都没有谈到这个,但它似乎是一个随机的应用程序 killer ,如果我们不明确处理这个问题,它会迫使用户重新安装(并可能丢失大量数据)。

最佳答案

MOC 的主要功能是表示独立于格式的抽象存储。它将所有对象存储在内存中,并使用事务机制来提交任何更改。因此,当您在 MOC 中插入/删除/编辑某些对象时,它们只会在内存中发生变化,而不会在持久存储中发生变化(无论是 SQLite 数据库、XML 文件还是其他)。只有在您调用 save: 方法时才会提交更改。

至于 NSOperation 和文件处理:如果你想停止一些操作,你应该为此调用 cancel。来自文档:

This method does not force your operation code to stop. Instead, it updates the object’s internal flags to reflect the change in state. If the operation has already finished executing, this method has no effect. Canceling an operation that is currently in an operation queue, but not yet executing, makes it possible to remove the operation from the queue sooner than usual.

这意味着如果在取消操作时有一些 IO 操作正在运行,操作将等到它完成。

此外,尽管有 Core Data 事务机制,但您应该为任何不受其管理的数据(如果需要)实现自己的事务机制。

关于iphone - 当线程在保存时被杀死时,如何防止 NSManagedObjectContext 破坏数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6207922/

相关文章:

iphone - cocos2d : How to set a timer

iphone - 当当前选定的表格单元格移出屏幕后,如何向其发送消息?

javascript - 放大 google map api 3 [ios]

iphone - 如何在 coredata 上下文中使用预填充的数据库

ios - 如何将数组保存到实体的属性?

ios - 阻止 SKSpriteNode 离开 View (Swift)

iphone - iPhone 中这些控件的替代品有哪些

iphone - 如何配置live555框架进行iphone应用程序开发?

ios - 我如何命名和控制 iOS 游戏中的个别 child ?

ios - 将 Swift._SwiftDeferredNSArray' (0x1096d26b8) 获取到核心数据中的 'NSMutableArray