Class

NSManagedObject

A generic class that implements all the basic behavior required of a Core Data model object.

Declaration

@interface NSManagedObject : NSObject

Overview

It is not possible to use instances of direct subclasses of NSObject (or any other class not inheriting from NSManagedObject) with a managed object context. You may create custom subclasses of NSManagedObject, although this is not always required. If no custom logic is needed, a complete Object graph can be formed with NSManagedObject instances.

A managed object is associated with an entity description (an instance of NSEntityDescription) that provides metadata about the object (including the name of the entity that the object represents and the names of its attributes and relationships) and with a managed object context that tracks changes to the object graph. It is important that a managed object is properly configured for use with Core Data. If you instantiate a managed object directly, you must call the designated initializer (initWithEntity:insertIntoManagedObjectContext:).

Data Storage

In some respects, an NSManagedObject acts like a dictionary—it is a generic container object that efficiently provides storage for the properties defined by its associated NSEntityDescription object. NSManagedObject provides support for a range of common types for attribute values, including string, date, and number (see NSAttributeDescription for full details). There is therefore commonly no need to define instance variables in subclasses. Sometimes, however, you want to use types that are not supported directly, such as colors and C structures. For example, in a graphics application you might want to define a Rectangle entity that has attributes color and bounds that are an instance of NSColor and an NSRect struct respectively. For some types you can use a transformable attribute, for others this may require you to create a subclass of NSManagedObject.

Faulting

Managed objects typically represent data held in a persistent store. In some situations a managed object may be a “fault”—an object whose property values have not yet been loaded from the external data store—see Faulting and Uniquing for more details. When you access persistent property values, the fault “fires” and the data is retrieved from the store automatically. This can be a comparatively expensive process (potentially requiring a round trip to the persistent store), and you may wish to avoid unnecessarily firing a fault.

You can safely invoke the following methods on a fault without causing it to fire: isEqual:, hash, superclass, class, self, isProxy, isKindOfClass:, isMemberOfClass:, conformsToProtocol:, respondsToSelector:, description, managedObjectContext, entity, objectID, isInserted, isUpdated, isDeleted, faultingState, and isFault. Since isEqual and hash do not cause a fault to fire, managed objects can typically be placed in collections without firing a fault. Note, however, that invoking key-value coding methods on the collection object might in turn result in an invocation of valueForKey: on a managed object, which would fire the fault.

Although the description method does not cause a fault to fire, if you implement a custom description method that accesses the object’s persistent properties, this will cause a fault to fire. You are strongly discouraged from overriding description in this way.

Subclassing Notes

In combination with the entity description in the managed object model, NSManagedObject provides a rich set of default behaviors including support for arbitrary properties and value validation. There are, however, many reasons why you might wish to subclass NSManagedObject to implement custom features; in doing so, though, you must not disrupt Core Data’s behavior.

Methods You Must Not Override

NSManagedObject itself customizes many features of NSObject so that managed objects can be properly integrated into the Core Data infrastructure. Core Data relies on NSManagedObject’s implementation of the following methods, which you therefore absolutely must not override: primitiveValueForKey:, setPrimitiveValue:forKey:, isEqual:, hash, superclass, class, self, isProxy, isKindOfClass:, isMemberOfClass:, conformsToProtocol:, respondsToSelector:, managedObjectContext, entity, objectID, isInserted, isUpdated, isDeleted, and isFault, alloc, allocWithZone:, new, instancesRespondToSelector:, instanceMethodForSelector:, methodForSelector:, methodSignatureForSelector:, instanceMethodSignatureForSelector:, or isSubclassOfClass:.

Methods You Should Not Override

As with any class, you are strongly discouraged from overriding the key-value observing methods such as willChangeValueForKey: and didChangeValueForKey:withSetMutation:usingObjects:. You are discouraged from overriding description—if this method fires a fault during a debugging operation, the results may be unpredictable. You are also discouraged from overriding initWithEntity:insertIntoManagedObjectContext:, or dealloc. Changing values in the initWithEntity:insertIntoManagedObjectContext: method will not be noticed by the context and if you are not careful, those changes may not be saved. Most initialization customization should be performed in one of the awake… methods. If you do override initWithEntity:insertIntoManagedObjectContext:, you must make sure you adhere to the requirements set out in the method description (see initWithEntity:insertIntoManagedObjectContext:).

You are discouraged from overriding dealloc because didTurnIntoFault is usually a better time to clear values—a managed object may not be reclaimed for some time after it has been turned into a fault. Core Data does not guarantee that dealloc will be called in all scenarios (such as when the application quits); therefore you should not include required side effects (like saving or changes to the file system, user preferences, and so on) in these methods.

In summary, for initWithEntity:insertIntoManagedObjectContext: and dealloc, it is important to remember that Core Data reserves exclusive control over the life cycle of the managed object (that is, raw memory management). This is so that the framework is able to provide features such as uniquing and by consequence relationship maintenance as well as much better performance than would be otherwise possible.

Additional Override Considerations

The following methods are intended to be fine grained and not perform large scale operations. You must not fetch or save in these methods. In particular, they should not have side effects on the managed object context:

  • initWithEntity:insertIntoManagedObjectContext:

  • didTurnIntoFault

  • willTurnIntoFault

  • dealloc

In addition to methods you should not override, there are others that if you do override you should invoke the superclass’s implementation first, including awakeFromInsert, awakeFromFetch, and validation methods. You should not modify relationships in awakeFromFetch—see the method description for details.

Custom Accessor Methods

Typically, there is no need to write custom accessor methods for properties that are defined in the entity of a managed object’s corresponding managed object model. Should you wish or need to do so, though, there are several implementation patterns you must follow. These are described in Managed Object Accessor Methods in Core Data Programming Guide.

Core Data automatically generates accessor methods (and primitive accessor methods) for you. For attributes and to-one relationships, Core Data generates the standard get and set accessor methods; for to-many relationships, Core Data generates the indexed accessor methods as described in Achieving Basic Key-Value Coding Compliance in Key-Value Coding Programming Guide. You do however need to declare the accessor methods or use Objective-C properties to suppress compiler warnings. For a full discussion, see Managed Object Accessor Methods in Core Data Programming Guide.

Custom Instance Variables

By default, NSManagedObject stores its properties in an internal structure as objects, and in general Core Data is more efficient working with storage under its own control rather using custom instance variables.

NSManagedObject provides support for a range of common types for attribute values, including string, date, and number (see NSAttributeDescription for full details). If you want to use types that are not supported directly, such as colors and C structures, you can either use transformable attributes or create a subclass of NSManagedObject.

Sometimes it may be convenient to represent variables as scalars—in a drawing applications, for example, where variables represent dimensions and x and y coordinates and are frequently used in calculations. To represent attributes as scalars, you declare instance variables as you would in any other class. You also need to implement suitable accessor methods as described in Managed Object Accessor Methods.

If you define custom instance variables, for example, to store derived attributes or other transient properties, you should clean up these variables in didTurnIntoFault rather than dealloc.

Validation Methods

NSManagedObject provides consistent hooks for validating property and inter-property values. You typically should not override validateValue:forKey:error:, instead you should implement methods of the form validate<Key>:error:, as defined by the NSKeyValueCoding protocol. If you want to validate inter-property values, you can override validateForUpdate: and/or related validation methods.

You should not call validateValue:forKey:error: within custom property validation methods—if you do so you will create an infinite loop when validateValue:forKey:error: is invoked at runtime. If you do implement custom validation methods, you should typically not call them directly. Instead you should call validateValue:forKey:error: with the appropriate key. This ensures that any constraints defined in the managed object model are applied.

If you implement custom inter-property validation methods (such as validateForUpdate:), you should call the superclass’s implementation first. This ensures that individual property validation methods are also invoked. If there are multiple validation failures in one operation, you should collect them in an array and add the array—using the key NSDetailedErrorsKey—to the userInfo dictionary in the NSError object you return. For an example, see Managed Object Validation.

Topics

Initializing a Managed Object

initWithEntity:insertIntoManagedObjectContext:

Initializes a managed object and inserts it into the specified managed object context.

initWithContext:

Initializes a managed object and inserts it into the specified managed object context.

Getting a Managed Object’s Identity

entity

The entity description of the managed object.

objectID

The object ID of the managed object.

entity

Returns the entity description that is associated with this subclass.

Getting State Information

managedObjectContext

The managed object context with which the managed object is registered.

hasChanges

A Boolean value that indicates whether the managed object has been inserted, has been deleted, or has unsaved changes.

inserted

A Boolean value that indicates whether the managed object has been inserted in a managed object context.

updated

A Boolean value that indicates whether the managed object has unsaved changes.

deleted

A Boolean value that indicates whether the managed object will be deleted during the next save.

fault

A Boolean value that indicates whether the managed object is a fault.

faultingState

The faulting state of the managed object.

hasFaultForRelationshipNamed:

Returns a Boolean value that indicates whether the relationship for a given key is a fault.

hasPersistentChangedValues

A Boolean value that indicates whether the managed object has persistent changes.

Managing Change Events

contextShouldIgnoreUnmodeledPropertyChanges

Returns a Boolean value that indicates whether instances of the class should be marked as having changes if an unmodeled property is changed.

awakeFromFetch

Provides an opportunity to add code into the life cycle of the managed object when it is being fulfilled from a fault.

awakeFromInsert

Provides an opportunity to add code into the life cycle of the managed object when it is initially created.

awakeFromSnapshotEvents:

Provides an opportunity to add code into the life cycle of the managed object when it is being fulfilled from a snapshot.

changedValues

Returns a dictionary containing the keys and (old) values of persistent properties that have been changed since last fetching or saving the managed object.

changedValuesForCurrentEvent

Returns a dictionary containing the keys and old values of persistent properties that have changed since the last posting of NSManagedObjectContextObjectsDidChangeNotification.

committedValuesForKeys:

Returns a dictionary of the last fetched or saved values of the managed object for the properties specified by the given keys.

prepareForDeletion

Provides an opportunity to add code into the life cycle of the managed object when it is about to be deleted.

willSave

Provides an opportunity to add code into the life cycle of the managed object when it is about to be saved.

didSave

Provides an opportunity to add code into the life cycle of the managed object after the managed object’s context completes a save operation.

willTurnIntoFault

Provides an opportunity to add code into the life cycle of the managed object before it is converted to a fault.

didTurnIntoFault

Provides an opportunity to add code into the life cycle of the managed object when it is turned into a fault.

fetchRequest

Returns a new fetch request initialized with the entity represented by this subclass.

Supporting Key-Value Coding

valueForKey:

Returns the value for the property specified by key.

setValue:forKey:

Sets the specified property of the managed object to the specified value.

mutableSetValueForKey:

Returns a mutable set that provides read-write access to the unordered to-many relationship specified by a given key.

primitiveValueForKey:

Returns the value for the specified property from the managed object’s private internal storage .

setPrimitiveValue:forKey:

Sets in the managed object's private internal storage the value of a given property.

objectIDsForRelationshipNamed:

Returns the object IDs for all of the managed objects that are in the named relationship.

Managing Data Validation

validateValue:forKey:error:

Validates a property value for a given key.

validateForDelete:

Determines whether the managed object can be deleted in its current state.

validateForInsert:

Determines whether the managed object can be inserted in its current state.

validateForUpdate:

Determines whether the managed object's current state is valid.

Validation Error Codes

Error codes related to validation of managed object properties.

NSValidationKeyErrorKey

The key for the key that failed to validate for a validation error.

NSValidationObjectErrorKey

The key for the object that failed to validate for a validation error.

NSValidationPredicateErrorKey

For predicate-based validation, the key for the predicate for the condition that failed to validate.

NSValidationValueErrorKey

If non-nil, the key for the value for the key that failed to validate for a validation error.

Supporting Key-Value Observing

automaticallyNotifiesObserversForKey:

Returns a Boolean value that indicates whether the receiver provides automatic support for key-value observing change notifications for the given key.

didAccessValueForKey:

Provides support for key-value observing access notification.

observationInfo

Returns the observation info of the managed object.

setObservationInfo:

Sets the observation info of the managed object.

willAccessValueForKey:

Provides support for key-value observing access notification.

didChangeValueForKey:

Provides an opportunity to respond when a value of a given property has changed.

didChangeValueForKey:withSetMutation:usingObjects:

Provides an opportunity to respond when a change was made to a specified to-many relationship.

willChangeValueForKey:

Provides an opportunity to respond when a value of a given property is about to change.

willChangeValueForKey:withSetMutation:usingObjects:

Provides an opportunity to respond when a change is about to be made to a specified to-many relationship.

Reinitializing Values

NSSnapshotEventType

Constants that specify the reason the managed object may need to reinitialize its values.

Relationships

Inherits From

See Also

First Steps

Making Core Data Your Model Layer

Learn how Core Data decreases the amount of code you need to develop and access your app's model layer.