核心数据和托管对象上下文

Sam*_*mui 3 core-data nsmanagedobjectcontext ios

我是Core Data的新手,我对如何以正确的方式做事情有一些疑问.我想我需要一个temporaryManagedObjectContext来处理临时实体,而用户正在编辑一个新实体.当用户点击保存该数据时,我想在persistedManagecObjectContext中插入这些实体,然后保存saveContext.实现这一目标的最佳做法是什么?由于我不想在临时环境中保存,因此必须使用线程?

谢谢你的知识!

Emm*_* Ay 6

您需要将临时ManagedObjectContext(MOC)中的更改合并到持久化的ManagedObjectContext(MOC)中.这是我如何实现这一目标的一个例子.我使用线程(每个线程一个MOC),但我很确定它应该没有线程也可以正常工作.

您可以调用此方法将更改保存在tempMOC中:

- (void) saveNewEntry {
    NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];

    // Subscribe to "NSManagedObjectContextDidSaveNotification"
    // ..which is sent when "[tempMOC save];" is called.
    [dnc addObserver: self 
            selector: @selector(mergeChanges:) 
                name: NSManagedObjectContextDidSaveNotification 
              object: tempMOC];

    // Save changes
    [tempMOC save];

    // Remove subscribtion
    [dnc removeObserver: self 
                   name: NSManagedObjectContextDidSaveNotification 
                 object: tempMOC];

}
Run Code Online (Sandbox Code Playgroud)

......将发出以下通知:

- (void) mergeChanges: (NSNotification*) saveNotification {

    // If youre using threads, this is necessary:
    [self performSelectorOnMainThread: @selector(mergeToMainContext:) 
                           withObject: saveNotification 
                        waitUntilDone: NO]; 

    // ...otherwise, you could do the merge in this method
    // [persistedMOC mergeChangesFromContextDidSaveNotification: saveNotification];
}
Run Code Online (Sandbox Code Playgroud)

...反过来调用:

- (void) mergeToMainContext: (NSNotification*) saveNotification {

    [persistedMOC mergeChangesFromContextDidSaveNotification: saveNotification];

}
Run Code Online (Sandbox Code Playgroud)