保存上下文时,项目不会添加到Core Data

时间:2016-06-18 18:36:40

标签: ios swift core-data

我正在尝试构建核心数据应用,并且我正在使用基于this本书的一些代码。

为了简化代码我有这样的事情:

class City: NSManagedObject {
    @NSManaged public private(set) var name: String
    @NSManaged public private(set) var population: Int

    public static func insert(context: NSManagedObjectContext, name: String, population: Int) -> City {

        let city: City = context.insertObject()
        city.name = name
        city.population = population

        return city
    }
}


extension NSManagedObjectContext {
    public func insertObject<A: NSManagedObject>() -> A {
        guard let obj = NSEntityDescription.insertNewObjectForEntityForName("City", inManagedObjectContext: self) as? A else {
            fatalError("Wrong object type")
        }

        return obj
    }

    public func saveOrRoleback() -> Bool {

        do {
            try save()
            return true
        } catch {
            rollback()
            return false
        }
    }

    public func performChanges(block: () -> ()) {

        performBlockAndWait {
            block()
            print(self.saveOrRoleback())
        }
    }
}


func addCity() {
    self.context.performChanges {
        City.insert(self.context, name: self.name.text!, amount: Int(self.population.text!))
    }
}

当我添加新城市时,save()方法在上下文中调用saveOrRollback()方法时,我没有收到任何错误,它会返回true。
但是没有添加数据。我试图检查sql文件并且为空。

对核心数据不熟悉有人可以指出我在哪里寻找问题吗?我希望保存时出现错误或其他内容,但一切似乎都正常,但数据库一直是空的。

编辑: - 添加核心数据设置

public func createContext() -> NSManagedObjectContext {

    let context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    context.persistentStoreCoordinator = createStoreCoordinator()

    return context
}

private func createStoreCoordinator() -> NSPersistentStoreCoordinator {

    let psc = NSPersistentStoreCoordinator(managedObjectModel: model.managedObjectModel)

    try! psc.addPersistentStoreWithType(model.storeType.type, configuration: nil, URL: model.storeURL, options: nil)

    return psc
}

// Main VC
override func viewDidLoad() {
    super.viewDidLoad()

    let model = CoreDataModel(modelName: modelName, modelBundle: modelBundle!, storeType: .SQLite(DocumentsDirectoryURL()))
    let factory = CoreDataFactory(model: model)

    context = factory.createContext()

    self.todayViewController = storyboard?.instantiateViewControllerWithIdentifier("TodayViewController") as! TodayViewController
    self.todayViewController.context = context
}

编辑2: - 添加数据后的SQL调试

-06-18 22:31:15.042 Savings+[1100:39698] CoreData: sql: BEGIN EXCLUSIVE
2016-06-18 22:31:15.043 Savings+[1100:39698] CoreData: sql: SELECT Z_MAX FROM Z_PRIMARYKEY WHERE Z_ENT = ?
2016-06-18 22:31:15.043 Savings+[1100:39698] CoreData: sql: UPDATE Z_PRIMARYKEY SET Z_MAX = ? WHERE Z_ENT = ? AND Z_MAX = ?
2016-06-18 22:31:15.043 Savings+[1100:39698] CoreData: sql: COMMIT
2016-06-18 22:31:15.045 Savings+[1100:39698] CoreData: sql: BEGIN EXCLUSIVE
2016-06-18 22:31:15.045 Savings+[1100:39698] CoreData: sql: INSERT INTO ZTRANSACTION(Z_PK, Z_ENT, Z_OPT, ZAMOUNT, ZDATE, ZNAME, ZTYPE) VALUES(?, ?, ?, ?, ?, ?, ?)
2016-06-18 22:31:15.045 Savings+[1100:39698] CoreData: sql: COMMIT
2016-06-18 22:31:15.046 Savings+[1100:39698] CoreData: sql: pragma page_count
2016-06-18 22:31:15.046 Savings+[1100:39698] CoreData: annotation: sql execution time: 0.0003s
2016-06-18 22:31:15.046 Savings+[1100:39698] CoreData: sql: pragma freelist_count

1 个答案:

答案 0 :(得分:1)

As discussed in comments/chat:

  1. Remember that the default journal mode for CoreData SQLite databases uses WAL mode, so you need to ensure any sql reader recognises those files. It's generally easier to use a fetch in your code than to read the sqlite files directly.
  2. Try using SQLDebug mode to see what is actually being read/written from/to sqlite.
  3. In this case, it transpired that you had a default predicate on your fetch request which excluded all the objects you have saved; removing the predicate shows that the data is there and your save is working correctly.