2016年1月25日 星期一

建立CoreData之後,新增修改Model要刪掉重裝?

你是否有遇過新增修改CoreData欄位之後,雖然可以build過,但一執行app就crash的問題?(我有)

其實很簡單,因為你改了原來資料庫的結構,在執行時app找不到對應的欄位做操作,所以直接請你吃一個abort()
那麼要如何來解決這個問題呢?
請使用者刪掉重裝就好了........(誤)

解決方式,就是把你的修改當作一個新的版本的Model,再做新舊的版本之間的對應。
CoreData有提供一套Automatic Migration機制來做這件事。
步驟如下
1. 在NSPersistentStoreCoordinator的設定中開啟Automatic Migration選項(紅色部份)
    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
        var failureReason = "There was an error creating or loading the application's saved data."
        let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true,
            NSInferMappingModelAutomaticallyOption: true]
        
        do {
            try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: mOptions)
        } catch {
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
            dict[NSLocalizedFailureReasonErrorKey] = failureReason

            dict[NSUnderlyingErrorKey] = error as NSError
            let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
            NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
            abort()
        }
        
        return coordinator
    }()

2. 點選yourModel.xcdatamodeld,到上方選單Editor -> Add Model Version... 新增一個新版本

3. 點選yourModel.xcdatamodeld,到右側選單中把Model Version的current改為你的新版本,改好你會看到yourModel.xcdatamodeld下面的新版本上有一個小綠勾。

4. 在新版本對你的欄位做新增或修改,注意不要改動到原來的版本!那是拿來做參照的。

5. Run,crash bye bye

沒有留言:

張貼留言