Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting started with Core Data

I am having trouble understanding how Core Data works conceptually and in terms of code.

I get that there is a coordinator and a context. I also get that there is state management. How do they work together?

I don't understand how I can store, say, an image and a few strings as an object.

Let's say I want to retrieve the image and the strings later. What do I do?

Where do I save my state? How?

What does my code look like? I would really appreciate a bare-bones code sample here, because I'm really confused.

like image 418
Moshe Avatar asked Jul 28 '10 18:07

Moshe


1 Answers

These are some of the best tutorials I've found:

  • Best tutorial I've found
  • Another good, multipage tutorial
  • Very good explaination of concepts
  • Apple Doc, might help with the concepts
  • Little Cheatsheet

As for your quesstions:

I get that there is a coordinator and a context. I also get that there is state management. How do they work together?

The persistent store coordinator is what manages the place your data is actually being stored, be that a SQLlite DB or a XML file or whatever. The coordinator is the abstraction so you don't have to worry about what type of storage is in the backend.

The Managed Object Context is how you interact with the Persistent Store Coordinator. Think of it as your scratch pad. You create and modify Managed Objects from the Managed Object Context.

I don't understand how I can store, say, an image and a few strings as an object. Let's say I want to retrieve the image and the strings later. What do I do?

If you look through some of the above tutorials, you'll see how to pull objects out of the managed object context. A NSString would simply be stored as a string attribute on a managed object, like so:

[managedObject setValue:@"TestString" forKey:@"SomeStringProperty"];

I'm not quite sure about images as I've never stored an image in Core Data before. I know anything that can be serialized can be stored as a transformable attribute. Here's a post about storing UIImages in Core Data

Where do I save my state? How?

You simply call the 'save' method on your managed object context. Like so:

[context save:&error]
like image 176
ACBurk Avatar answered Oct 12 '22 12:10

ACBurk