核心数据获取并保存在不同的线程中

时间:2018-03-12 08:00:00

标签: swift multithreading core-data nsoperation

我创建了一个Coredatacontroller类来处理所有Core数据操作。获取当前上下文的一种方法是在这个类中编写的。

func getCurrentContext() -> NSManagedObjectContext {
        var curMOC:NSManagedObjectContext? = self.managedObjectContext
        let thisThread:Thread = Thread.current
        print("This thread: ", thisThread)
        if thisThread == Thread.main {
            if curMOC != nil {
                return curMOC!
            }
            let coordinator:NSPersistentStoreCoordinator? = self.persistentStoreCoordinator
            if coordinator != nil {
                curMOC = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
                curMOC?.persistentStoreCoordinator = coordinator
            }
            return curMOC!
        }
        // if this is some other thread....
        // Get the current context from the same thread..
        var threadManagedObjectContext:NSManagedObjectContext? = thisThread.threadDictionary.object(forKey:"MOC_KEY") as? NSManagedObjectContext;
        // Return separate MOC for each new thread
        if threadManagedObjectContext != nil {
            return threadManagedObjectContext!;
        }

        let coordinator:NSPersistentStoreCoordinator? = self.persistentStoreCoordinator
        if coordinator != nil {
            threadManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
            threadManagedObjectContext?.persistentStoreCoordinator = coordinator
            threadManagedObjectContext?.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
            thisThread.threadDictionary.setObject(threadManagedObjectContext!, forKey: "MOC_KEY" as NSCopying)
        }
        return threadManagedObjectContext!;
    }

我正在使用NSOperation子类上传一些图像,因此对于每个图像,正在制作NSOperation的对象。在NSOperation的内部完成块中,我从CoreData获取一些数据并更新它。

问题: 提取不会返回核心数据中存在的记录 如果在获取方法中我使用mainmanagedobjectcontext然后我得到记录但是当我用currentcontext保存它时它不反映核心数据的变化。 我也在NSOperation子类中编写了通知观察器方法,但该方法永远不会被调用。 请建议应该做什么!!

1 个答案:

答案 0 :(得分:0)

处理来自不同线程的CoreData对象非常复杂。我建议使用CoreStore,它将为您完成所有上下文处理。

示例设置:

@app.route('/handle_data', methods=['GET','POST'])

def handle_data():
   print("Got data")
   data=request.form['my_Data'] // What should be here

示例对象创建:

let dataStack: DataStack = {
    let dataStack = DataStack(xcodeModelName: "ModelName")
    do {
        try dataStack.addStorageAndWait()
    } catch let error {
        print("Cannot set up database storage: \(error)")
    }
    return dataStack
}()

示例对象获取:

func addUser(id: String, name: String) {
    dataStack.perform(asynchronous: { transaction in
        let user = transaction.create(Into<User>())
        user.id = id
        user.name = name
    }, completion: { _ in })
}