< Previous PageNext Page > Hide TOC

Initialization

There are several situations in which an object's properties may be initialized. Most obviously, when an object is first created—you typically establish values in this case in init or another custom initializer. You may also, however, want to initialize an object in a different way when it is extracted from an archive. In this situation, you can customize the initialization in initWithCoder:. Core Data provides special methods for initialization at different stages in an object's life-cycle.

Core Data Initialization

Core Data defines a number of methods to support initialization, validation, and reporting on saving. Core Data also allows you to put default initial values for attributes into the managed object model. This may obviate the need for many custom initialization methods. Should you nevertheless need to perform additional initialization, Core Data provides special methods—awakeFromInsert and awakeFromFetch—that you can override to perform initialization in two different circumstances. Note that, should you wish to perform initialization in all circumstances, it also specifies a designated initializer for NSManagedObject: initWithEntity:insertIntoManagedObjectContext:.

The initializer methods awakeFromInsert and awakeFromFetch allow you to discriminate between two different situations. awakeFromInsert is invoked automatically when a newly created managed object is first inserted into a managed object context. This happens only once in the entire lifetime of the object. You can use this method to, for example, set a creation date stamp. awakeFromFetch is invoked on subsequent occasions when a managed object is retrieved from a persistent store, whether as a result of your executing a fetch request, or as a result of a fault firing. You can use awakeFromFetch to, for example, calculate derived property values.

Because you must initialize an NSManagedObject instance with initWithEntity:insertIntoManagedObjectContext:, you cannot readily use managed objects with an archiver (put another way, you cannot an easily implement an initWithCoder:: method for a managed object class). You might instead implement a custom class that handles the decoding and then returns a real managed object instead of self from initWithCoder:.



< Previous PageNext Page > Hide TOC


© 2008 Apple Inc. All Rights Reserved. (Last updated: 2008-02-08)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.