NSManagedObject Class Reference
| Inherits from | |
| Conforms to | |
| Framework | /System/Library/Frameworks/CoreData.framework |
| Availability | Available in iOS 3.0 and later. |
| Declared in | NSManagedObject.h |
| Companion guides | |
Overview
NSManagedObject is a generic class that implements all the basic behavior required of a Core Data model object. 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—see “Non-Standard Persistent Attributes”.
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 Are Discouraged From Overriding
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); you should therefore not in these methods include required side effects (like saving or changes to the file system, user preferences, and so on).
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.
Methods to 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:didTurnIntoFaultwillTurnIntoFaultdealloc
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 “Key-Value Coding Accessor Methods” 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, as described in “Non-Standard Persistent Attributes”.
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 “Model Object Validation”.
Tasks
Initializing a Managed Object
Getting a Managed Object’s Identity
Getting State Information
-
– managedObjectContext -
– hasChanges -
– isInserted -
– isUpdated -
– isDeleted -
– isFault -
– faultingState -
– hasFaultForRelationshipNamed:
Managing Life Cycle and Change Events
-
+ contextShouldIgnoreUnmodeledPropertyChanges -
– awakeFromFetch -
– awakeFromInsert -
– awakeFromSnapshotEvents: -
– changedValues -
– changedValuesForCurrentEvent -
– committedValuesForKeys: -
– prepareForDeletion -
– dealloc -
– willSave -
– didSave -
– willTurnIntoFault -
– didTurnIntoFault
Supporting Key-Value Coding
-
– valueForKey: -
– setValue:forKey: -
– mutableSetValueForKey: -
– primitiveValueForKey: -
– setPrimitiveValue:forKey:
Validation
Supporting Key-Value Observing
Class Methods
automaticallyNotifiesObserversForKey:
Returns a Boolean value that indicates whether the receiver provides automatic support for key-value observing change notifications for the given key.
Parameters
- key
The name of one of the receiver's properties.
Return Value
YES if the receiver provides automatic support for key-value observing change notifications for key, otherwise NO.
Discussion
The default implementation for NSManagedObject returns NO for modeled properties, and YES for unmodeled properties. For more about key-value observation, see Key-Value Observing Programming Guide.
contextShouldIgnoreUnmodeledPropertyChanges
Returns a Boolean value that indicates whether instances of the class should be marked as having changes if an unmodeled property is changed.
Return Value
YES if instances of the class should be marked as having changes if an unmodeled property is changed, otherwise NO.
Discussion
The default value is YES.
Availability
- Available in iOS 3.0 and later.
See Also
-
– changedValuesForCurrentEvent -
hasChanges(NSManagedObjectContext)
Declared In
NSManagedObject.hInstance Methods
awakeFromFetch
Invoked automatically by the Core Data framework after the receiver has been fetched.
Discussion
You typically use this method to compute derived values or to recreate transient relationships from the receiver’s persistent properties.
The managed object context’s change processing is explicitly disabled around this method so that you can use public setters to establish transient values and other caches without dirtying the object or its context. Because of this, however, you should not modify relationships in this method as the inverse will not be set.
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hawakeFromInsert
Invoked automatically by the Core Data framework when the receiver is first inserted into a managed object context.
Discussion
You typically use this method to initialize special default property values. This method is invoked only once in the object's lifetime.
If you want to set attribute values in an implementation of this method, you should typically use primitive accessor methods (either setPrimitiveValue:forKey: or—better—the appropriate custom primitive accessors). This ensures that the new values are treated as baseline values rather than being recorded as undoable changes for the properties in question.
Special Considerations
If you create a managed object then perform undo operations to bring the managed object context to a state prior to the object’s creation, then perform redo operations to bring the managed object context back to a state after the object’s creation, awakeFromInsert is not invoked a second time.
You are typically discouraged from performing fetches within an implementation of awakeFromInsert. Although it is allowed, execution of the fetch request can trigger the sending of internal Core Data notifications which may have unwanted side-effects. For example, in OS X, an instance of NSArrayController may end up inserting a new object into its content array twice.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hawakeFromSnapshotEvents:
Invoked automatically by the Core Data framework when the receiver is reset due to an undo, redo, or other multi-property state change.
Parameters
- flags
A bitmask of
didChangeValueForKey:constants to denote the event or events that led to the method being invoked.For possible values, see “NSSnapshotEventType.”
Discussion
You typically use this method to compute derived values or to recreate transient relationships from the receiver’s persistent properties.
If you want to set attribute values and need to avoid emitting key-value observation change notifications, you should use primitive accessor methods (either setPrimitiveValue:forKey: or—better—the appropriate custom primitive accessors). This ensures that the new values are treated as baseline values rather than being recorded as undoable changes for the properties in question.
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hchangedValues
Returns a dictionary containing the keys and (new) values of persistent properties that have been changed since last fetching or saving the receiver.
Return Value
A dictionary containing as keys the names of persistent properties that have changed since the receiver was last fetched or saved, and as values the new values of the properties.
Discussion
This method only reports changes to properties that are defined as persistent properties of the receiver, not changes to transient properties or custom instance variables. This method does not unnecessarily fire relationship faults.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hchangedValuesForCurrentEvent
Returns a dictionary containing the keys and (new) values of persistent properties that have changed since the last posting of NSManagedObjectContextObjectsDidChangeNotification.
Return Value
A dictionary containing as keys the names of persistent properties that have changed since the last posting of NSManagedObjectContextObjectsDidChangeNotification.
Discussion
This method only reports changes to properties that are defined as persistent properties of the receiver, not changes to transient properties or custom instance variables. This method does not unnecessarily fire relationship faults.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
NSManagedObject.hcommittedValuesForKeys:
Returns a dictionary of the last fetched or saved values of the receiver for the properties specified by the given keys.
Parameters
- keys
An array containing names of properties of the receiver, or
nil.
Return Value
A dictionary containing the last fetched or saved values of the receiver for the properties specified by keys.
Discussion
This method only reports values of properties that are defined as persistent properties of the receiver, not values of transient properties or of custom instance variables.
You can invoke this method with the keys value of nil to retrieve committed values for all the receiver’s properties, as illustrated by the following example.
NSDictionary *allCommittedValues = |
[aManagedObject committedValuesForKeys:nil]; |
It is more efficient to use nil than to pass an array of all the property keys.
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hdealloc
Deallocates the memory occupied by the receiver.
Discussion
This method first invokes didTurnIntoFault.
You should typically not override this method—instead you should put “clean-up” code in prepareForDeletion or didTurnIntoFault.
See Also
didAccessValueForKey:
Provides support for key-value observing access notification.
Parameters
- key
The name of one of the receiver's properties.
Discussion
Together with willAccessValueForKey:, this method is used to fire faults, to maintain inverse relationships, and so on. Each read access must be wrapped in this method pair (in the same way that each write access must be wrapped in the willChangeValueForKey:/didChangeValueForKey: method pair). In the default implementation of NSManagedObject these methods are invoked for you automatically. If, say, you create a custom subclass that uses explicit instance variables, you must invoke them yourself, as in the following example.
- (NSString *)firstName |
{ |
[self willAccessValueForKey:@"firstName"]; |
NSString *rtn = firstName; |
[self didAccessValueForKey:@"firstName"]; |
return rtn; |
} |
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hdidChangeValueForKey:
Invoked to inform the receiver that the value of a given property has changed.
Parameters
- key
The name of the property that changed.
Discussion
For more details, see Key-Value Observing Programming Guide.
You must not override this method.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hdidChangeValueForKey:withSetMutation:usingObjects:
Invoked to inform the receiver that the specified change was made to a specified to-many relationship.
Parameters
- inKey
The name of a property that is a to-many relationship.
- inMutationKind
The type of change that was made.
- inObjects
The objects that were involved in the change (see
NSKeyValueSetMutationKind).
Discussion
For more details, see Key-Value Observing Programming Guide.
You must not override this method.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hdidSave
Invoked automatically by the Core Data framework after the receiver’s managed object context completes a save operation.
Discussion
You can use this method to notify other objects after a save, and to compute transient values from persistent values.
This method can have “side effects” on the persistent values, however any changes you make using standard accessor methods will by default dirty the managed object context and leave your context with unsaved changes. Moreover, if the object’s context has an undo manager, such changes will add an undo operation. For document-based applications, changes made in didSave will therefore come into the next undo grouping, which can lead to “empty” undo operations from the user's perspective. You may want to disable undo registration to avoid this issue.
The sense of “save” in the method name is that of a database commit statement and so applies to deletions as well as to updates to objects. For subclasses, this method is therefore an appropriate locus for code to be executed when an object deleted as well as “saved to disk.” You can find out if an object is marked for deletion with isDeleted.
Special Considerations
You cannot attempt to resurrect a deleted object in didSave.
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hdidTurnIntoFault
Invoked automatically by the Core Data framework when the receiver is turned into a fault.
Discussion
You use this method to clear out custom data caches—transient values declared as entity properties are typically already cleared out by the time this method is invoked (see, for example, refreshObject:mergeChanges:).
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hentity
Returns the entity description of the receiver.
Return Value
The entity description of the receiver.
Discussion
If the receiver is a fault, calling this method does not cause it to fire.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hfaultingState
Returns a value that indicates the faulting state of the receiver.
Return Value
0 if the object is fully initialized as a managed object and not transitioning to or from another state, otherwise some other value.
Discussion
The method allow you to determine if an object is in a transitional phase when receiving a key-value observing change notification.
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hhasChanges
Returns a Boolean value that indicates whether the receiver has been inserted, has been deleted, or has unsaved changes.
Return Value
YES if the receiver has been inserted, has been deleted, or has unsaved changes, otherwise NO.
Discussion
The result is the equivalent of OR-ing the values of isInserted, isDeleted, and isUpdated.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
NSManagedObject.hhasFaultForRelationshipNamed:
Returns a Boolean value that indicates whether the relationship for a given key is a fault.
Parameters
- key
The name of one of the receiver’s relationships.
Return Value
YES if the relationship for for the key key is a fault, otherwise NO.
Discussion
If the specified relationship is a fault, calling this method does not result in the fault firing.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hinitWithEntity:insertIntoManagedObjectContext:
Initializes the receiver and inserts it into the specified managed object context.
Parameters
- entity
The entity of which to create an instance.
The model associated with context's persistent store coordinator must contain entity.
- context
The context into which the new instance is inserted.
Return Value
An initialized instance of the appropriate class for entity.
Discussion
NSManagedObject uses dynamic class generation to support the Objective-C 2 properties feature (see “Declared Properties”) by automatically creating a subclass of the class appropriate for entity.initWithEntity:insertIntoManagedObjectContext: therefore returns an instance of the appropriate class for entity. The dynamically-generated subclass will be based on the class specified by the entity, so specifying a custom class in your model will supersede the class passed to alloc.
If context is not nil, this method invokes [context insertObject:self] (which causes awakeFromInsert to be invoked).
You are discouraged from overriding this method—you should instead override awakeFromInsert and/or awakeFromFetch (if there is logic common to these methods, it should be factored into a third method which is invoked from both). If you do perform custom initialization in this method, you may cause problems with undo and redo operations.
In many applications, there is no need to subsequently assign a newly-created managed object to a particular store—see assignObject:toPersistentStore:. If your application has multiple stores and you do need to assign an object to a specific store, you should not do so in a managed object's initializer method. Such an assignment is controller- not model-level logic.
Special Considerations
If you override initWithEntity:insertIntoManagedObjectContext:, you must ensure that you set self to the return value from invocation of super’s implementation, as shown in the following example:
- (id)initWithEntity:(NSEntityDescription*)entity insertIntoManagedObjectContext:(NSManagedObjectContext*)context |
{ |
self = [super initWithEntity:entity insertIntoManagedObjectContext:context]; |
if (self != nil) { |
// Perform additional initialization. |
} |
return self; |
} |
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hisDeleted
Returns a Boolean value that indicates whether the receiver will be deleted during the next save.
Return Value
YES if the receiver will be deleted during the next save, otherwise NO.
Discussion
The method returns YES if Core Data will ask the persistent store to delete the object during the next save operation. It may return NO at other times, particularly after the object has been deleted. The immediacy with which it will stop returning YES depends on where the object is in the process of being deleted.
If the receiver is a fault, invoking this method does not cause it to fire.
Availability
- Available in iOS 3.0 and later.
See Also
-
– isFault -
– isInserted -
– isUpdated -
deletedObjects(NSManagedObjectContext) -
NSManagedObjectContextObjectsDidChangeNotification(NSManagedObjectContext)
Declared In
NSManagedObject.hisFault
Returns a Boolean value that indicates whether the receiver is a fault.
Return Value
YES if the receiver is a fault, otherwise NO.
Discussion
Knowing whether an object is a fault is useful in many situations when computations are optional. It can also be used to avoid growing the object graph unnecessarily (which may improve performance as it can avoid time-consuming fetches from data stores).
If this method returns NO, then the receiver's data must be in memory. However, if this method returns YES, it does not imply that the data is not in memory. The data may be in memory, or it may not, depending on many factors influencing caching
If the receiver is a fault, calling this method does not cause it to fire.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hisInserted
Returns a Boolean value that indicates whether the receiver has been inserted in a managed object context.
Return Value
YES if the receiver has been inserted in a managed object context, otherwise NO.
Discussion
If the receiver is a fault, calling this method does not cause it to fire.
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hisUpdated
Returns a Boolean value that indicates whether the receiver has unsaved changes.
Return Value
YES if the receiver has unsaved changes, otherwise NO.
Discussion
The receiver has unsaved changes if it has been updated since its managed object context was last saved.
If the receiver is a fault, calling this method does not cause it to fire.
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hmanagedObjectContext
Returns the managed object context with which the receiver is registered.
Return Value
The managed object context with which the receiver is registered.
Discussion
This method may return nil if the receiver has been deleted from its context.
If the receiver is a fault, calling this method does not cause it to fire.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hmutableSetValueForKey:
Returns a mutable set that provides read-write access to the unordered to-many relationship specified by a given key.
Parameters
- key
The name of one of the receiver's to-many relationships.
Discussion
If key is not a property defined by the model, the method raises an exception.
This method is overridden by NSManagedObject to access the managed object’s generic dictionary storage unless the receiver’s class explicitly provides key-value coding compliant accessor methods for key.
Special Considerations
For performance reasons, the proxy object returned by managed objects for mutableSetValueForKey: does not support set<Key>: style setters for relationships. For example, if you have a to-many relationship employees of a Department class and implement accessor methods employees and setEmployees:, then manipulate the relationship using the proxy object returned by mutableSetValueForKey:@"employees", setEmployees: is not invoked. You should implement the other mutable proxy accessor overrides instead (see “Managed Object Accessor Methods” in Core Data Programming Guide).
objectID
Returns the object ID of the receiver.
Return Value
The object ID of the receiver.
Discussion
If the receiver is a fault, calling this method does not cause it to fire.
Availability
- Available in iOS 3.0 and later.
See Also
-
URIRepresentation(NSManagedObjectID)
Declared In
NSManagedObject.hobservationInfo
Returns the observation info of the receiver.
Return Value
The observation info of the receiver.
Discussion
For more about observation information, see Key-Value Observing Programming Guide.
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hprepareForDeletion
Invoked automatically by the Core Data framework when the receiver is about to be deleted.
Discussion
You can implement this method to perform any operations required before the object is deleted, such as custom propagation before relationships are torn down, or reconfiguration of objects using key-value observing.
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hprimitiveValueForKey:
Returns from the receiver’s private internal storage the value for the specified property.
Parameters
- key
The name of one of the receiver's properties.
Return Value
The value of the property specified by key. Returns nil if no value has been set.
Discussion
This method does not invoke the access notification methods (willAccessValueForKey: and didAccessValueForKey:). This method is used primarily by subclasses that implement custom accessor methods that need direct access to the receiver’s private storage.
Special Considerations
Subclasses should not override this method.
The following points also apply:
Primitive accessor methods are only supported on modeled properties. If you invoke a primitive accessor on an unmodeled property, it will instead operate upon a random modeled property. (The debug libraries and frameworks (available from Apple Developer website) have assertions to test for passing unmodeled keys to these methods.)
You are strongly encouraged to use the dynamically-generated accessors rather than using this method directly (for example,
primitiveName:instead ofprimitiveValueForKey:@"name"). The dynamic accessors are much more efficient, and allow for compile-time checking.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hself
Returns the receiver.
Discussion
Subclasses must not override this method.
Note for EOF developers: Core Data does not rely on this method for faulting—see instead willAccessValueForKey:.
setObservationInfo:
Sets the observation info of the receiver.
Parameters
- value
The new observation info for the receiver.
Discussion
For more about observation information, see Key-Value Observing Programming Guide.
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hsetPrimitiveValue:forKey:
Sets in the receiver's private internal storage the value of a given property.
Parameters
- value
The new value for the property specified by key.
- key
The name of one of the receiver's properties.
Discussion
Sets in the receiver’s private internal storage the value of the property specified by key to value. If key identifies a to-one relationship, relates the object specified by value to the receiver, unrelating the previously related object if there was one. Given a collection object and a key that identifies a to-many relationship, relates the objects contained in the collection to the receiver, unrelating previously related objects if there were any.
This method does not invoke the change notification methods (willChangeValueForKey: and didChangeValueForKey:). It is typically used by subclasses that implement custom accessor methods that need direct access to the receiver’s private internal storage. It is also used by the Core Data framework to initialize the receiver with values from a persistent store or to restore a value from a snapshot.
Special Considerations
You must not override this method.
You should typically use this method only to modify attributes (usually transient), not relationships. If you try to set a to-many relationship to a new NSMutableSet object, it will (eventually) fail. In the unusual event that you need to modify a relationship using this method, you first get the existing set using primitiveValueForKey: (ensure the method does not return nil), create a mutable copy, and then modify the copy—as illustrated in the following example:
NSMutableSet *recentHires = [[dept primitiveValueForKey:@"recentHires"] mutableCopy]; |
if (recentHires != nil) { |
[recentHires removeAllObjects]; |
[dept setPrimitiveValue:recentHires forKey:@"recentHires"]; |
} |
If the relationship is bi-directional (that is, if an inverse relationship is specified) then you are also responsible for maintaining the inverse relationship (regardless of cardinality)—in contrast with Core Data's normal behavior described in “Using Managed Objects”.
The following points also apply:
Primitive accessor methods are only supported on modeled properties. If you invoke a primitive accessor on an unmodeled property, it will instead operate upon a random modeled property. (The debug libraries and frameworks from (available from the Apple Developer Website) have assertions to test for passing unmodeled keys to these methods.)
You are strongly encouraged to use the dynamically-generated accessors rather than using this method directly (for example,
setPrimitiveName:instead ofsetPrimitiveValue:newName forKey:@"name"). The dynamic accessors are much more efficient, and allow for compile-time checking.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hsetValue:forKey:
Sets the specified property of the receiver to the specified value.
Parameters
- value
The new value for the property specified by key.
- key
The name of one of the receiver's properties.
Discussion
If key is not a property defined by the model, the method raises an exception. If key identifies a to-one relationship, relates the object specified by value to the receiver, unrelating the previously related object if there was one. Given a collection object and a key that identifies a to-many relationship, relates the objects contained in the collection to the receiver, unrelating previously related objects if there were any.
This method is overridden by NSManagedObject to access the managed object’s generic dictionary storage unless the receiver’s class explicitly provides key-value coding compliant accessor methods for key.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hvalidateForDelete:
Determines whether the receiver can be deleted in its current state.
Parameters
- error
If the receiver cannot be deleted in its current state, upon return contains an instance of
NSErrorthat describes the problem.
Return Value
YES if the receiver can be deleted in its current state, otherwise NO.
Discussion
An object cannot be deleted if it has a relationship has a “deny” delete rule and that relationship has a destination object.
NSManagedObject’s implementation sends the receiver’s entity description a message which performs basic checking based on the presence or absence of values.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hvalidateForInsert:
Determines whether the receiver can be inserted in its current state.
Parameters
- error
If the receiver cannot be inserted in its current state, upon return contains an instance of
NSErrorthat describes the problem.
Return Value
YES if the receiver can be inserted in its current state, otherwise NO.
Special Considerations
Subclasses should invoke super’s implementation before performing their own validation, and should combine any error returned by super’s implementation with their own (see “Model Object Validation”).
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hvalidateForUpdate:
Determines whether the receiver’s current state is valid.
Parameters
- error
If the receiver's current state is invalid, upon return contains an instance of
NSErrorthat describes the problem.
Return Value
YES if the receiver's current state is valid, otherwise NO.
Discussion
NSManagedObject’s implementation iterates through all of the receiver’s properties validating each in turn. If this results in more than one error, the userInfo dictionary in the NSError returned in error contains a key NSDetailedErrorsKey; the corresponding value is an array containing the individual validation errors. If you pass NULL as the error, validation will abort after the first failure.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hvalidateValue:forKey:error:
Validates a property value for a given key.
Parameters
- value
A pointer to an object.
- key
The name of one of the receiver's properties.
- error
If value is not a valid value for key (and cannot be coerced), upon return contains an instance of
NSErrorthat describes the problem.
Return Value
YES if value is a valid value for key (or if value can be coerced into a valid value for key), otherwise NO.
Discussion
This method is responsible for two things: coercing the value into an appropriate type for the object, and validating it according to the object’s rules.
The default implementation provided by NSManagedObject consults the object’s entity description to coerce the value and to check for basic errors, such as a null value when that isn’t allowed and the length of strings when a field width is specified for the attribute. It then searches for a method of the form validate<Key>:error: and invokes it if it exists.
You can implement methods of the form validate<Key>:error: to perform validation that is not possible using the constraints available in the property description. If it finds an unacceptable value, your validation method should return NO and in error an NSError object that describes the problem. For more details, see “Model Object Validation”. For inter-property validation (to check for combinations of values that are invalid), see validateForUpdate: and related methods.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hvalueForKey:
Returns the value for the property specified by key.
Parameters
- key
The name of one of the receiver's properties.
Return Value
The value of the property specified by key.
Discussion
If key is not a property defined by the model, the method raises an exception. This method is overridden by NSManagedObject to access the managed object’s generic dictionary storage unless the receiver’s class explicitly provides key-value coding compliant accessor methods for key.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hwillAccessValueForKey:
Provides support for key-value observing access notification.
Parameters
- key
The name of one of the receiver's properties.
Discussion
See didAccessValueForKey: for more details. You can invoke this method with the key value of nil to ensure that a fault has been fired, as illustrated by the following example.
[aManagedObject willAccessValueForKey:nil]; |
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hwillChangeValueForKey:
Invoked to inform the receiver that the value of a given property is about to change.
Parameters
- key
The name of the property that will change.
Discussion
For more details, see Key-Value Observing Programming Guide.
You must not override this method.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hwillChangeValueForKey:withSetMutation:usingObjects:
Invoked to inform the receiver that the specified change is about to be made to a specified to-many relationship.
Parameters
- inKey
The name of a property that is a to-many relationship
- inMutationKind
The type of change that will be made.
- inObjects
The objects that were involved in the change (see
NSKeyValueSetMutationKind).
Discussion
For more details, see Key-Value Observing Programming Guide.
You must not override this method.
Availability
- Available in iOS 3.0 and later.
Declared In
NSManagedObject.hwillSave
Invoked automatically by the Core Data framework when the receiver’s managed object context is saved.
Discussion
This method can have “side effects” on persistent values. You can use it to, for example, compute persistent values from other transient or scratchpad values.
If you want to update a persistent property value, you should typically test for equality of any new value with the existing value before making a change. If you change property values using standard accessor methods, Core Data will observe the resultant change notification and so invoke willSave again before saving the object’s managed object context. If you continue to modify a value in willSave, willSave will continue to be called until your program crashes.
For example, if you set a last-modified timestamp, you should check whether either you previously set it in the same save operation, or that the existing timestamp is not less than a small delta from the current time. Typically it’s better to calculate the timestamp once for all the objects being saved (for example, in response to an NSManagedObjectContextWillSaveNotification).
If you change property values using primitive accessors, you avoid the possibility of infinite recursion, but Core Data will not notice the change you make.
The sense of “save” in the method name is that of a database commit statement and so applies to deletions as well as to updates to objects. For subclasses, this method is therefore an appropriate locus for code to be executed when an object deleted as well as “saved to disk.” You can find out if an object is marked for deletion with isDeleted.
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hwillTurnIntoFault
Invoked automatically by the Core Data framework before receiver is converted to a fault.
Discussion
This method is the companion of the didTurnIntoFault method. You can use it to (re)set state which requires access to property values (for example, observers across keypaths). The default implementation does nothing.
Availability
- Available in iOS 3.0 and later.
See Also
Declared In
NSManagedObject.hConstants
The following constants relate to errors returned following validation failures.
NSDetailedErrorsKey | If multiple validation errors occur in one operation, they are collected in an array and added with this key to the “top-level error” of the operation. |
NSValidationKeyErrorKey | Key for the key that failed to validate for a validation error. |
NSValidationPredicateErrorKey | For predicate-based validation, 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. |
NSSnapshotEventType
Constants returned from awakeFromSnapshotEvents: to denote the reason why a managed object may need to reinitialize values.
enum {
NSSnapshotEventUndoInsertion = 1 << 1,
NSSnapshotEventUndoDeletion = 1 << 2,
NSSnapshotEventUndoUpdate = 1 << 3,
NSSnapshotEventRollback = 1 << 4,
NSSnapshotEventRefresh = 1 << 5,
NSSnapshotEventMergePolicy = 1 << 6
};
typedef NSUInteger NSSnapshotEventType;
Constants
NSSnapshotEventUndoInsertionSpecifies a change due to undo from insertion.
Available in iOS 3.0 and later.
Declared in
NSManagedObject.h.NSSnapshotEventUndoDeletionSpecifies a change due to undo from deletion.
Available in iOS 3.0 and later.
Declared in
NSManagedObject.h.NSSnapshotEventUndoUpdateSpecifies a change due to a property-level undo.
Available in iOS 3.0 and later.
Declared in
NSManagedObject.h.NSSnapshotEventRollbackSpecifies a change due to the managed object context being rolled back.
Available in iOS 3.0 and later.
Declared in
NSManagedObject.h.NSSnapshotEventRefreshSpecifies a change due to the managed object being refreshed.
Available in iOS 3.0 and later.
Declared in
NSManagedObject.h.NSSnapshotEventMergePolicySpecifies a change due to conflict resolution during a save operation.
Available in iOS 3.0 and later.
Declared in
NSManagedObject.h.
© 2011 Apple Inc. All Rights Reserved. (Last updated: 2011-05-01)