在一个线程上创建上下文,在另一个线程上访问没有造成任何问题

时间:2019-03-23 11:26:52

标签: ios core-data persistence

在Apple文档中,其写为​​“托管对象上下文绑定到初始化时与之关联的线程(队列)。”

意味着在一个线程上创建的上下文必须在该线程上使用,在另一个线程上使用它将导致问题。

在任何情况下都会出现问题。在下面的代码中,另一个线程使用在主线程上创建的上下文将更改保存到持久性存储中。

func addTwoUsers() {

        //1) get reference to app delegate singleton instance
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }

        //2) We need context from container Entity needs context to create objects
        let managedObjectContext = appDelegate.persistentContainer.viewContext
        let userFetchRequest = NSFetchRequest<User>(entityName: "User")

        do {
            //4) Execute fetch request
            let users: [User] = try managedObjectContext.fetch(userFetchRequest)
            print(users.count)

        }
        catch let error as NSError {
            print("Could not fetch. \(error), \(error.userInfo)")
        }

        DispatchQueue.global(qos: .background).async {
            //2) Created a User object

            let user = User(context: managedObjectContext)
            user.secondName = "User One Seond name"
            user.firstName = "ali"

            //2) Created a User object
            let secondUser = User(context: managedObjectContext)
            secondUser.secondName = "User Second Seond name"
            secondUser.firstName = "Not ali"

            //7) Save to persitsent store
            do {
                try managedObjectContext.save()
            } catch let error as NSError {
                print("Could not save. \(error), \(error.userInfo)")
            }

        }
    }

0 个答案:

没有答案