循环获取数据时,CoreData崩溃

时间:2018-06-27 18:19:15

标签: ios iphone swift core-data

我正在使用旧的xcdatamodel,它是在xcode 7.3中创建的(这很关键,因为在现代模型中我没有以下问题)。同时,仅将我的Tool Version的{​​{1}}更改为Xcode 9.0并不能解决此问题。

我正在xcdatamodel循环中获取数据,该线程用于上下文中。当我尝试获取已经获取一次的实体时,coreData会因for而崩溃。僵尸跟踪说EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP)

这是我的工作理念:

[CFString copy]: message sent to deallocated instance 0x608000676b40

这是上下文初始化程序:

LegacyDatabaser.context.perform {
    do {
        for _ in 0..<10 {
            let entity = try self.legacyDatabase.getEntity(forId:1)
            print(entity.some_string_property) // <- crash here
        }
    } catch {
        // ...
    }
}

class LegacyDatabaser {
     static var context: NSManagedObjectContext = LegacyDatabaseUtility.context
     // ...
}

这是数据获取程序:

class LegacyDatabaseUtility {
    fileprivate class var context: NSManagedObjectContext {
        //let context = NSManagedObjectContext(concurrencyType:.privateQueueConcurrencyType)
        //context.persistentStoreCoordinator = storeContainer.persistentStoreCoordinator
        //return context // This didn't help also
        return storeContainer.newBackgroundContext() 
    }
    private static var storeContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name:"MyDBName")
        container.loadPersistentStores { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        }
        return container
    }()
}

并且:

func getEntity(forId id: NSNumber) throws -> MyEntity? {

    // Create predicate
    let predicate = NSPredicate(format:"id_local == %@", id)

    // Find items in db
    let results = try LegacyDatabaseUtility.find(predicate:predicate, sortDescriptors:nil, in:LegacyDatabaser.context)

    // Check it
    if results.count == 1 {
        if let result = results.first as? MyEntity {
            return result        
        } else {
            return nil
        }
    } else {
        return nil
    }
}

我没有并行处理上下文,我确定我使用了正确的线程和上下文(我也测试了主上下文,结果相同)。我做错了,为什么重新获取同一实体失败?

1 个答案:

答案 0 :(得分:0)

如果有人遇到任何怪异的崩溃(如上文所述),请检查NSManagedObject中的属性名称。就我而言,崩溃发生在调用new_id属性上,我猜这是一个保留名称。重命名此属性后,崩溃停止了。