Tag Archives: NSManagedObject

How to add a custom initialiser to a Managed Object in Core Data

NSManagedObjects behave differently to NSObjects on many levels. If you’d like to add custom start-up behaviour in your NSManagedObjects, you’ll have noticed that overriding the standard init method isn’t working.

Instead, we can use the awakeFromFetch method. This is called automatically when a managed object is retrieved from the Core Data stack:

Use this to set default values or initialise methods in your NSManagedObject classes.

How to delete an NSManagedObject in Core Data

You can delete individual objects by using the NSManagedObjectContext method deleteObject, like so:

To delete all managed objects from your store, you can use a for-in loop:

I assume that you have created managed object sub classes. I’m also assuming that you have access to save the context. If not, here’s what the method looks like (taken from AppDelegate with Core Data template):

How to retrieve a Managed Object in Core Data Fetch Requests

Retrieving Managed Objects is somewhat more complex than creating them, mainly because you can filter what you’re getting back rather than retrieve everything that your store file has to offer.

Let’s first illustrate a basic NSFetchRequest. For the following examples I’m using the iOS Master/Detail template which provides an Entity called Event with a property called timeStamp. I’ve created custom subclasses for this entity. Press the add button a few times so we have some data, then quit the application.

Basic Fetch Request

Here’s how we can retrieve all our values using a basic Fetch Request:

This content is for members only.

How to create a Managed Object in Core Data

Assuming you’re using an app template that includes Core Data, you will have access to the Managed Object Context. In the simplest form, and without custom Entity classes setup, you can use key/value coding to set your object’s properties. In fact, the Master/Detail template does this.

Here’s an example for an Entity named Event with two properties (myKey and anotherKey):

If you have created custom NSManagedObject subclasses for your Entity then you can create an object like this:

The KVC method will always work, regardless if you have custom classes or not. Custom Classes have the advantage that you can add custom behaviour (i.e. methods), and of course code completion in Xcode.

Note that these snippets will create an object, but your values are only stored once you save the Managed Object Context: