Swift core data does not store the data permanently

倾然丶 夕夏残阳落幕 提交于 2019-12-24 16:54:29

问题


I also have the same problem with (This guy) but he doesn't tell the solution. Therefore, I have to ask you how I can do ? I have an Entity called Rabbits, Attributes are birth_date,breed_date,cage_no,dam_earnum,nes_date,pal_date,rabbit_id,sire_earnum

My core data store :

var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
        var context:NSManagedObjectContext = appDel.managedObjectContext!
        var request = NSFetchRequest(entityName: "Rabbits")
        var result:NSArray = context.executeFetchRequest(request, error: nil)!
        request.includesSubentities = false
        request.returnsObjectsAsFaults = false
var rabbits = NSEntityDescription.insertNewObjectForEntityForName("Rabbits", inManagedObjectContext: context) as! NSManagedObject
        rabbits.setValue(buckTextField.text, forKey: "sire_earnum")
        rabbits.setValue(doeTextField.text, forKey: "dam_earnum")
        rabbits.setValue(cageTextField.text, forKey: "cage_no")
        rabbits.setValue(breedDate, forKey: "breed_date")
        rabbits.setValue(palDate, forKey: "pal_date")
        rabbits.setValue(nesDate, forKey: "nes_date")
        rabbits.setValue(birthDate, forKey: "birth_date")
        rabbits.setValue(index, forKey: "rabbit_id")
        context.save(nil)

My code to retrieve data :

var result: Array = delegate.managedObjectContext.executeFetchRequest(NSFetchRequest(entityName: "Rabbits"), error: &err)
println("reslut \(result)")

So when I retrieve, it gives result with data..but its not stored permanently..if I quit and run the app then previous data has gone..can anyone tell me what is the issue with my code...

There are some suggestion of Joride that tell me to show the out put of the return value of save method that true or false with this following code :

println("delegate: \(delegate); MOC: \(delegate.managedObjectContext)")

I got the message : delegate: <BreedRabbit.AppDelegate: 0x7f8ad9d03b20>; MOC: <NSManagedObjectContext: 0x7f8ad9c300b0>

How I can do next ?


回答1:


I think you are fetching wrong entity with your fetchrequest. Try change this:

var result: Array = delegate.managedObjectContext.executeFetchRequest(NSFetchRequest(entityName: "Friend"), error: &err)

to this:

var result: Array = delegate.managedObjectContext.executeFetchRequest(NSFetchRequest(entityName: "Rabbits"), error: &err)



回答2:


A couple of possible reasons for data not being actually saved are:

  • Using NSInMemoryStoreType when creating your persistent store coordinator;

  • Having entity properties set to Transient in the model editor.

Please, check that to rule out these possible causes.



来源:https://stackoverflow.com/questions/30012086/swift-core-data-does-not-store-the-data-permanently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!