Core Data

2018-06-26  本文已影响23人  EmptyWalker

使用Core Data出现以下错误

2018-06-26 21:12:02.205266+0800 FoodPin[7492:5238267] [error] error: Mutating a managed object 0x1c423ba40 <x-coredata:///Restaurant/t8A97D93A-CC28-4859-A59A-DB120381D3842> (0x1c428b7c0) after it has been removed from its context.
CoreData: error: Mutating a managed object 0x1c423ba40 <x-coredata:///Restaurant/t8A97D93A-CC28-4859-A59A-DB120381D3842> (0x1c428b7c0) after it has been removed from its context.
2018-06-26 21:12:04.296395+0800 FoodPin[7492:5238267] [error] error: Mutating a managed object 0x1c423ba40 <x-coredata:///Restaurant/t8A97D93A-CC28-4859-A59A-DB120381D3842> (0x1c428b7c0) after it has been removed from its context.
CoreData: error: Mutating a managed object 0x1c423ba40 <x-coredata:///Restaurant/t8A97D93A-CC28-4859-A59A-DB120381D3842> (0x1c428b7c0) after it has been removed from its context.
2018-06-26 21:12:06.433615+0800 FoodPin[7492:5238267] [error] error: Mutating a managed object 0x1c423ba40 <x-coredata:///Restaurant/t8A97D93A-CC28-4859-A59A-DB120381D3842> (0x1c428b7c0) after it has been removed from its context.
CoreData: error: Mutating a managed object 0x1c423ba40 <x-coredata:///Restaurant/t8A97D93A-CC28-4859-A59A-DB120381D3842> (0x1c428b7c0) after it has been removed from its context.

查找资料,定位原因是由于context创建多次,或者managed object被删除了,根据定位寻找context,通过断点获取context的地址,发现每次的context都不一样,然后查看context的persistentContainer的创建方法如下:

var persistentContainer: NSPersistentContainer {
        let container = NSPersistentContainer(name: "FoodPin")
        container.loadPersistentStores { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unsolved error \(error), \(error.userInfo)")
            }
        }
        return container
    }

每次都是创建一个新的persistentContainer,自然context也就不唯一了。

解决

修改persistentContainer代码如下:

lazy var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "FoodPin")
        container.loadPersistentStores { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unsolved error \(error), \(error.userInfo)")
            }
        }
        return container
    }()

即可解决报错

上一篇下一篇

猜你喜欢

热点阅读