Swift 核心数据不会永久存储数据
Posted
技术标签:
【中文标题】Swift 核心数据不会永久存储数据【英文标题】:Swift core data does not store data permanently 【发布时间】:2014-07-03 05:48:15 【问题描述】:我有一个名为“Friend”的实体。属性是名称和年龄。这里我已经实现了桥接,因为 Friend 的 NSManagedObject 类有 .h 和 .m 文件。我存储数据的代码:
var err: NSError?
var delegate:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var friend:Friend = Friend(entity: NSEntityDescription.entityForName("Friend", inManagedObjectContext: delegate.managedObjectContext), insertIntoManagedObjectContext: delegate.managedObjectContext)
friend.friendName = "Mani"
friend.friendAge = "23"
delegate.managedObjectContext.save(&err)
我的数据检索代码
var result: Array = delegate.managedObjectContext.executeFetchRequest(NSFetchRequest(entityName: "Friend"), error: &err)
println("reslut \(result)")
所以当我检索时,它会给出带有数据的结果..但它不会永久存储..如果我退出并运行应用程序,那么以前的数据已经消失了..谁能告诉我我的代码有什么问题...
这是示例项目https://github.com/rnystrom/Swift-CoreData 我从 Github 获得的..这个项目也有同样的问题..
【问题讨论】:
Baaad Design: var delegate:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate 不管怎样,你检查过 save 方法的返回值吗,如果返回 false,打印错误(像这样: println("(err)") ?它可能会给你一个线索。 我刚刚打印了错误..它为零..如果我的代码设计不好,你能建议如何编写好的设计吗? 错误是 nil 并且返回值是 false 吗?因为如果save方法返回true,就真的save了,没有报错。如果该方法返回 false 并且没有错误,则 managedObjectContext 很可能是 nil。对于 appDelegate 问题,请开始阅读:hollance.com/2012/02/dont-abuse-the-app-delegate 感谢教程..是的..没有错误..但没有永久保存..你知道为什么吗? 【参考方案1】:save方法的返回值是什么,是真还是假?如果您将其放在使用 save 方法的行之前,您能否显示下一行的输出:
println("delegate: \(delegate); MOC: \(delegate.managedObjectContext)")
【讨论】:
委托:<_ttc12samplethur0311appdelegate>; MOC:以上是关于Swift 核心数据不会永久存储数据的主要内容,如果未能解决你的问题,请参考以下文章