开发者

Saving data from ViewControllres (Core Data)

I looked through a core data tutorial which puts the core data code in the 开发者_运维技巧AppDelegate class that is created upon creating a Window project. I was able to successfully save and retrieve data from the premade AppDelegate class.

My question is, if i have a ViewController that saves data, how do i go about saving data from that specific class.

  • Do i need to redefine the persistent store and managedObjectModel in that class?
  • If that is the case, what is the programmatic way to do it (since previously it was generated for me) i.e what methods/instancevariables/properties do i need to declare.

Standing by for any clarifications there may be


No need to go through the app delegate or redefine persistent store etc. All you need is a reference to the managedObjectContext. Normally, this is a property (say, of a view controller) that you can set from the outside after creation and easily access from inside the view controller class (much easier than going through the app delegate!). You can pass this on easily to other view controllers, and read from and write to core data with the standard methods.

If you want to save your own objects, yes - you have to create your own managed object model (by modifying the one the template generated for you).


Why not just have a reference to your application delegate in the view controller you wish to save data in? You can then access the managed object context and call its save method as usual.

In the .h file of your view controller have a property of same type as you application delegate. Then in the viewDidLoad method in the .m file set the reference like this:

self.appDelegate = (MyApplicationDelegate*)[[UIApplication sharedApplication] delegate];

Then when you want to save you can access the application delegates managed object context like so:

[self.appDelegate.managedObjectContext save:&error];

Hope that helps, I wrote that off the top of my head so there might be some syntax errors but the compiler will let you know.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜