Getting started with Core Data
Asked Answered
C

3

11

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.

Cuvette answered 28/7, 2010 at 18:41 Comment(0)
H
24

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

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]
Haplite answered 28/7, 2010 at 21:6 Comment(3)
You can store NSData objects in Core Data, so to save an image, get it's data (probably using UIImagePNGRepresentation()) and store that. To retrieve the image, get the NSData object from Core Data and then use UIImage's +imageWithData method to get a UIImage.Cavallaro
The second tutorial you linked is coming back with a Error 400 Bad Request at the time of writing this comment.Readability
Well Ray Wanderlich tutorial was very bad. It jumped into some Python scripts in second part which did not make sense at all. :-|Homogenize
E
2

Go through Apple's Core Data tutorial.

Eduino answered 28/7, 2010 at 18:54 Comment(0)
J
1

There are tons of documentation and source code available from Apple to get you started.

Jeraldjeraldine answered 28/7, 2010 at 18:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.