Core Data 使用 Swift 保存数据

Posted

技术标签:

【中文标题】Core Data 使用 Swift 保存数据【英文标题】:Core Data saving data with Swift 【发布时间】:2014-10-19 09:26:33 【问题描述】:

如果在键盘上单击返回,我想存储数据(文本)。但它不起作用。 我想显示保存在表格视图单元格中的文本,并且在下次启动应用程序后也应该可用。

我的代码:

    func textFieldShouldReturn(textField: UITextField) -> Bool 

    tableViewData.append(textField.text)
    textField.text = ""
    self.tableView.reloadData()
    textField.resignFirstResponder()

    // Reference to our app delegate

    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate

    // Reference moc

    let contxt: NSManagedObjectContext = appDel.managedObjectContext!
    let en = NSEntityDescription.entityForName("note", inManagedObjectContext: contxt)

    // Create instance of pur data model an initialize

    var newNote = Model(entity: en!, insertIntoManagedObjectContext: contxt)

    // Map our properties

    newNote.note = textField.text

    // Save our context

    contxt.save(nil)
    println(newNote)

    return true

日志:

CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Users/Patti/Library/Developer/CoreSimulator/Devices/A70306D7-76BE-489A-82B3-FBAA9390D5A4/data/Containers/Data/Application/FC51C1B7-416B-463E-B976-C175642A4B34/Documents/Note_App.sqlite options:(null) ... returned error Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)" UserInfo=0x7fa79add8080 metadata=
NSPersistenceFrameworkVersion = 519;
NSStoreModelVersionHashes =     
    Notes = <674765e4 00e077d5 e3b4d2ca 2795eee2 42850989 4a2a825a 0c289097 387aa3a5>;
;
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers =     (
    ""
);
NSStoreType = SQLite;
NSStoreUUID = "8348BBED-7C75-4EF5-B73C-075E8719696E";
"_NSAutoVacuumLevel" = 2;
, reason=The model used to open the store is incompatible with the one used to      create the store with userInfo dictionary 
metadata =     
    NSPersistenceFrameworkVersion = 519;
    NSStoreModelVersionHashes =         
        Notes = <674765e4 00e077d5 e3b4d2ca 2795eee2 42850989 4a2a825a 0c289097 387aa3a5>;
    ;
    NSStoreModelVersionHashesVersion = 3;
    NSStoreModelVersionIdentifiers =         (
        ""
    );
    NSStoreType = SQLite;
    NSStoreUUID = "8348BBED-7C75-4EF5-B73C-075E8719696E";
    "_NSAutoVacuumLevel" = 2;
;
reason = "The model used to open the store is incompatible with the one used to  create the store";

2014-10-19 12:05:19.559 Note App[2450:43299] Unresolved error Optional(Error   Domain=YOUR_ERROR_DOMAIN Code=9999 "Failed to initialize the application's saved data"    UserInfo=0x7fa79addb450 NSLocalizedFailureReason=There was an error creating or loading  the application's saved data., NSLocalizedDescription=Failed to initialize the  application's saved data, NSUnderlyingError=0x7fa79add80c0 "The operation couldn’t be  completed. (Cocoa error 134100.)"), Optional([NSLocalizedFailureReason: There was an  error creating or loading the application's saved data., NSLocalizedDescription: Failed   to initialize the application's saved data, NSUnderlyingError: Error  Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error  134100.)" UserInfo=0x7fa79add8080 metadata=
NSPersistenceFrameworkVersion = 519;
NSStoreModelVersionHashes =     
    Notes = <674765e4 00e077d5 e3b4d2ca 2795eee2 42850989 4a2a825a 0c289097  387aa3a5>;
;
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers =     (
    ""
);
NSStoreType = SQLite;
NSStoreUUID = "8348BBED-7C75-4EF5-B73C-075E8719696E";
"_NSAutoVacuumLevel" = 2;
, reason=The model used to open the store is incompatible with the one used to  create the store])

【问题讨论】:

什么不起作用?为什么要将 nil 传递给 save 函数,而不是给它一个错误对象并检查它以查看出现了什么问题(如果有的话)? 我用我的崩溃日志更新了这个问题。 查看最后一行,上面写着“reason=...”。粘贴崩溃日志非常好,但如果您也阅读它会有所帮助。 【参考方案1】:

崩溃日志的最后一行告诉您出了什么问题。

自运行应用程序以来,您已经更改了模型。您要么需要启用自动迁移,以便自动更正此类更改,要么只需从模拟器中删除应用程序并再次运行它。

【讨论】:

是的,现在可以了。但是我在这行代码中遇到了一个新错误:var newNote = Model(entity: en!, insertIntoManagedObjectContext: context) 是说:fatal error: unexpectedly found nil while unwrapping an Optional value 这就是为什么显式解包选项是一个坏主意的原因,你失去了 Swift 内置的所有类型安全性。分配实体的行中有问题。

以上是关于Core Data 使用 Swift 保存数据的主要内容,如果未能解决你的问题,请参考以下文章

Swift 3 Core Data - 无法保存关系值

如何在 Swift 中将可转换属性保存到 Core Data

Swift 3 Core Data - 如何同步保存上下文?

如何将字符串保存到Core Data Swift

如何在 Swift 中的 Core Data 中保存多个项目

Swift 2.1 Core Data - 保存具有一对多关系的数据,但如果已经存在则不要添加异构数据