2016-01-20 54 views
5

我正在尝试我的第一个轻量级CoreData迁移。我阅读了两个轻量级迁移指南。这两个代码添加到CoreDataStack类,修改像NSPersistentStoreCoordinator变量并添加:如何在Swift中轻量级CoreData迁移

let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true, 
    NSInferMappingModelAutomaticallyOption: true] 

我的问题是,我有一个完美的功能应用使用CoreData,但我没有这样的类或类似的东西。 我的问题是,为什么这些项目假设我有这个课程,没有它我能实现轻量级移植吗?如果不是,我该如何添加它?

更多信息,如果必须回答

在9月,我建立使用CoreData的应用程序。这是我第一次使用CoreData,并遵循这个Ray Wenderlich指南。它运行得非常好,我完成了应用程序,现在它在商店。现在我想开始对应用程序进行一些更改,其中涉及新的CoreData属性和一些新实体。我读过,我需要设置一个新的模型版本。

我发现了一个Ray Wenderlich guide但它使用这个CoreDataStack.swift文件我没有:

CoreData Class

什么是令人沮丧的是,我设置CoreData使用他们指南,它不包括该文件!然后我去做一次移民,他们认为我有。

我在寻找另一种轻量级的迁移方法去,发现这个alternative它,我从来没有内置到我的CoreData也引用代号:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { 
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. 
// Create the coordinator and store 
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) 
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MyLog.sqlite") 
var error: NSError? = nil 
var failureReason = "There was an error creating or loading the application's saved data." 
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { 
    coordinator = nil 
    // Report any error we got. 
    var dict = [String: AnyObject]() 
    dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" 
    dict[NSLocalizedFailureReasonErrorKey] = failureReason 
    dict[NSUnderlyingErrorKey] = error 
    error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) 
    // Replace this with code to handle the error appropriately. 
    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
    NSLog("Unresolved error \(error), \(error!.userInfo)") 
    abort() 
} 

所以我读过的指南和理解90%的教程。我只是需要有人来看一看该原始CoreData教程,并告诉我,如果我没有CoreData类,我想补充的轻量级代码,如:

let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true, 
    NSInferMappingModelAutomaticallyOption: true] 

回答

8

迁移选项需用于将持久存储添加到持久存储协调器的调用中。您可以通过搜索addPersistentStoreWithType轻松找到这一行代码。

try coordinator!.addPersistentStoreWithType(
    NSSQLiteStoreType, configuration: nil, URL: url, options: mOptions) 

您的Core Data堆栈很可能位于AppDelegate类中,但无论它在哪里,都是您必须添加迁移选项的位置。

+0

谢谢!凌晨1点,但将在早上尝试,并标记正确,如果它的工作。你还可以对我提到的那类课程有所了解吗?为什么在本教程中,该类是由持久存储处理的? –

+0

谢谢,这似乎已经奏效。我没有得到我在教程中看到的控制台打印输出,显示了一个迁移,但我添加了属性和实体,然后运行该应用程序并没有任何问题。 –