Class: NSManagedObject

Inherits:
NSObject show all

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.

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods inherited from NSObject

#!, #!=, #!~, #, #==, #===, #=~, #Rational, #__callee__, #__method__, #__send__, #__type__, `, alloc, allocWithZone:, #autoContentAccessingProxy, autoload, autoload?, autorelease_pool, #awakeAfterUsingCoder:, binding, block_given?, caller, cancelPreviousPerformRequestsWithTarget:, cancelPreviousPerformRequestsWithTarget:selector:object:, catch, class, classFallbacksForKeyedArchiver, #classForCoder, #classForKeyedArchiver, classForKeyedUnarchiver, #clone, conformsToProtocol:, #copy, copyWithZone:, #define_singleton_method, description, display, #doesNotRecognizeSelector:, #dup, #enum_for, #eql?, #equal?, #extend, fail, #finalize, format, #forwardInvocation:, #forwardingTargetForSelector:, framework, #freeze, #frozen?, getpass, gets, global_variables, #init, initialize, #initialize_clone, #initialize_copy, #initialize_dup, #inspect, instanceMethodForSelector:, instanceMethodSignatureForSelector:, #instance_eval, #instance_exec, #instance_of?, #instance_variable_defined?, #instance_variable_get, #instance_variable_set, #instance_variables, instancesRespondToSelector:, isSubclassOfClass:, #is_a?, iterator?, #kind_of?, lambda, load, load_bridge_support_file, load_plist, local_variables, loop, #method, #methodForSelector:, #methodSignatureForSelector:, #methods, #mutableCopy, mutableCopyWithZone:, new, #nil?, open, p, #performSelector:onThread:withObject:waitUntilDone:, #performSelector:onThread:withObject:waitUntilDone:modes:, #performSelector:withObject:afterDelay:, #performSelector:withObject:afterDelay:inModes:, #performSelectorInBackground:withObject:, #performSelectorOnMainThread:withObject:waitUntilDone:, #performSelectorOnMainThread:withObject:waitUntilDone:modes:, print, printf, #private_methods, proc, #protected_methods, #public_method, #public_methods, #public_send, putc, puts, raise, rand, readline, readlines, #replacementObjectForCoder:, #replacementObjectForKeyedArchiver:, require, resolveClassMethod:, resolveInstanceMethod:, #respond_to?, #respond_to_missing?, select, #send, setVersion:, #singleton_methods, sprintf, srand, superclass, #taint, #tainted?, #tap, test, throw, #to_plist, #to_s, trace_var, trap, #trust, #untaint, untrace_var, #untrust, #untrusted?, version

Constructor Details

This class inherits a constructor from NSObject

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class NSObject

Class Method Details

+ (Boolean) automaticallyNotifiesObserversForKey(key)

Returns a Boolean value that indicates whether the receiver provides automatic support for key-value observing change notifications for the given key. 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.

Parameters:

  • key (String)

    The name of one of the receiver's properties.

Returns:

  • (Boolean)

    YES if the receiver provides automatic support for key-value observing change notifications for key, otherwise NO.

+ (Boolean) contextShouldIgnoreUnmodeledPropertyChanges

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

Returns:

  • (Boolean)

    YES if instances of the class should be marked as having changes if an unmodeled property is changed, otherwise NO.

Instance Method Details

- (Object) awakeFromFetch

Invoked automatically by the Core Data framework after the receiver has been fetched. 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. Important:  Subclasses must invoke super’s implementation before performing their own initialization.

Returns:

- (Object) awakeFromInsert

Invoked automatically by the Core Data framework when the receiver is first inserted into a managed object context. 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. Important:  Subclasses must invoke super’s implementation before performing their own initialization.

Returns:

- (Object) awakeFromSnapshotEvents(flags)

Invoked automatically by the Core Data framework when the receiver is reset due to an undo, redo, or other multi-property state change. 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. Important: Subclasses must invoke super’s implementation before performing their own initialization.

Parameters:

  • flags (NSSnapshotEventType)

    A bitmask of didChangeValueForKey: constants to denote the event or events that led to the method being invoked.For possible values, see “NSSnapshotEventType.”

Returns:

- (Hash) changedValues

Returns a dictionary containing the keys and (new) values of persistent properties that have been changed since last fetching or saving the receiver. 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.

Returns:

  • (Hash)

    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.

- (Hash) changedValuesForCurrentEvent

Returns a dictionary containing the keys and (new) values of persistent properties that have changed since the last posting of NSManagedObjectContextObjectsDidChangeNotification. 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.

Returns:

  • (Hash)

    A dictionary containing as keys the names of persistent properties that have changed since the last posting of NSManagedObjectContextObjectsDidChangeNotification.

- (Hash) committedValuesForKeys(keys)

Returns a dictionary of the last fetched or saved values of the receiver for the properties specified by the given keys. 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.It is more efficient to use nil than to pass an array of all the property keys.

Parameters:

  • keys (Array)

    An array containing names of properties of the receiver, or nil.

Returns:

  • (Hash)

    A dictionary containing the last fetched or saved values of the receiver for the properties specified by keys.

- (Object) dealloc

Deallocates the memory occupied by the receiver. This method first invokes didTurnIntoFault.You should typically not override this method—instead you should put “clean-up” code in prepareForDeletion or didTurnIntoFault.

Returns:

- (Object) didAccessValueForKey(key)

Provides support for key-value observing access notification. 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.

Parameters:

  • key (String)

    The name of one of the receiver's properties.

Returns:

- (Object) didChangeValueForKey(key)

Invoked to inform the receiver that the value of a given property has changed. For more details, see Key-Value Observing Programming Guide.You must not override this method.

Parameters:

  • key (String)

    The name of the property that changed.

Returns:

- (Object) didChangeValueForKey(inKey, withSetMutation:inMutationKind, usingObjects:inObjects)

Invoked to inform the receiver that the specified change was made to a specified to-many relationship. For more details, see Key-Value Observing Programming Guide.You must not override this method.

Parameters:

  • inKey (String)

    The name of a property that is a to-many relationship.

  • inMutationKind (NSKeyValueSetMutationKind)

    The type of change that was made.

  • inObjects (NSSet)

    The objects that were involved in the change (see NSKeyValueSetMutationKind).

Returns:

- (Object) didSave

Invoked automatically by the Core Data framework after the receiver’s managed object context completes a save operation. 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.

Returns:

- (Object) didTurnIntoFault

Invoked automatically by the Core Data framework when the receiver is turned into a fault. 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:).

Returns:

- (NSEntityDescription) entity

Returns the entity description of the receiver. If the receiver is a fault, calling this method does not cause it to fire.

Returns:

- (Integer) faultingState

Returns a value that indicates the faulting state of the receiver. The method allow you to determine if an object is in a transitional phase when receiving a key-value observing change notification.

Returns:

  • (Integer)

    0 if the object is fully initialized as a managed object and not transitioning to or from another state, otherwise some other value.

- (Boolean) hasChanges

Returns a Boolean value that indicates whether the receiver has been inserted, has been deleted, or has unsaved changes. The result is the equivalent of OR-ing the values of isInserted, isDeleted, and isUpdated.

Returns:

  • (Boolean)

    YES if the receiver has been inserted, has been deleted, or has unsaved changes, otherwise NO.

- (Boolean) hasFaultForRelationshipNamed(key)

Returns a Boolean value that indicates whether the relationship for a given key is a fault. If the specified relationship is a fault, calling this method does not result in the fault firing.

Parameters:

  • key (String)

    The name of one of the receiver’s relationships.

Returns:

  • (Boolean)

    YES if the relationship for for the key key is a fault, otherwise NO.

- (Object) initWithEntity(entity, insertIntoManagedObjectContext:context)

Initializes the receiver and inserts it into the specified managed object context. 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.Important:  This method is the designated initializer for NSManagedObject. You must not initialize a managed object simply by sending it init.

Parameters:

  • entity (NSEntityDescription)

    The entity of which to create an instance.The model associated with context’s persistent store coordinator must contain entity.

  • context (NSManagedObjectContext)

    The context into which the new instance is inserted.

Returns:

  • (Object)

    An initialized instance of the appropriate class for entity.

- (Boolean) isDeleted

Returns a Boolean value that indicates whether the receiver will be deleted during the next save. 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.

Returns:

  • (Boolean)

    YES if the receiver will be deleted during the next save, otherwise NO.

- (Boolean) isFault

Returns a Boolean value that indicates whether the receiver is a fault. 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 cachingIf the receiver is a fault, calling this method does not cause it to fire.

Returns:

  • (Boolean)

    YES if the receiver is a fault, otherwise NO.

- (Boolean) isInserted

Returns a Boolean value that indicates whether the receiver has been inserted in a managed object context. If the receiver is a fault, calling this method does not cause it to fire.

Returns:

  • (Boolean)

    YES if the receiver has been inserted in a managed object context, otherwise NO.

- (Boolean) isUpdated

Returns a Boolean value that indicates whether the receiver has unsaved changes. 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.

Returns:

  • (Boolean)

    YES if the receiver has unsaved changes, otherwise NO.

- (NSManagedObjectContext) managedObjectContext

Returns the managed object context with which the receiver is registered. 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.

Returns:

- (NSMutableSet) mutableSetValueForKey(key)

Returns a mutable set that provides read-write access to the unordered to-many relationship specified by a given key. 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.Important: You must not override this method.

Parameters:

  • key (String)

    The name of one of the receiver’s to-many relationships.

Returns:

- (NSManagedObjectID) objectID

Returns the object ID of the receiver. If the receiver is a fault, calling this method does not cause it to fire.Important: 

If the receiver has not yet been saved, the object ID is a temporary value that will change when the object is saved.

Returns:

- (Object) observationInfo

Returns the observation info of the receiver. For more about observation information, see Key-Value Observing Programming Guide.Important: You must not override this method.

Returns:

  • (Object)

    The observation info of the receiver.

- (Object) prepareForDeletion

Invoked automatically by the Core Data framework when the receiver is about to be deleted. 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.

Returns:

- (Object) primitiveValueForKey(key)

Returns from the receiver’s private internal storage the value for the specified property. 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.

Parameters:

  • key (String)

    The name of one of the receiver’s properties.

Returns:

  • (Object)

    The value of the property specified by key. Returns nil if no value has been set.

- (Object) self

Returns the receiver. Subclasses must not override this method.Note for EOF developers: Core Data does not rely on this method for faulting—see instead willAccessValueForKey:.

Returns:

- (Object) setObservationInfo(value)

Sets the observation info of the receiver. For more about observation information, see Key-Value Observing Programming Guide.

Parameters:

  • value (Object)

    The new observation info for the receiver.

Returns:

- (Object) setPrimitiveValue(value, forKey:key)

Sets in the receiver’s private internal storage the value of a given property. 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.

Parameters:

  • value (Object)

    The new value for the property specified by key.

  • key (String)

    The name of one of the receiver’s properties.

Returns:

- (Object) setValue(value, forKey:key)

Sets the specified property of the receiver to the specified value. 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.Important: You must not override this method.

Parameters:

  • value (Object)

    The new value for the property specified by key.

  • key (String)

    The name of one of the receiver’s properties.

Returns:

- (Boolean) validateForDelete(error)

Determines whether the receiver can be deleted in its current state. 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.Important:  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”).

Parameters:

  • error (Pointer)

    If the receiver cannot be deleted in its current state, upon return contains an instance of NSError that describes the problem.

Returns:

  • (Boolean)

    YES if the receiver can be deleted in its current state, otherwise NO.

- (Boolean) validateForInsert(error)

Determines whether the receiver can be inserted in its current state.

Parameters:

  • error (Pointer)

    If the receiver cannot be inserted in its current state, upon return contains an instance of NSError that describes the problem.

Returns:

  • (Boolean)

    YES if the receiver can be inserted in its current state, otherwise NO.

- (Boolean) validateForUpdate(error)

Determines whether the receiver’s current state is valid. 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.Important:  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”).

Parameters:

  • error (Pointer)

    If the receiver’s current state is invalid, upon return contains an instance of NSError that describes the problem.

Returns:

  • (Boolean)

    YES if the receiver’s current state is valid, otherwise NO.

- (Boolean) validateValue(value, forKey:key, error:error)

Validates a property value for a given key. 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:error: and invokes it if it exists.You can implement methods of the form validate: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.

Parameters:

  • value (Object)

    A pointer to an object.

  • key (String)

    The name of one of the receiver’s properties.

  • error (Pointer)

    If value is not a valid value for key (and cannot be coerced), upon return contains an instance of NSError that describes the problem.

Returns:

  • (Boolean)

    YES if value is a valid value for key (or if value can be coerced into a valid value for key), otherwise NO.

- (Object) valueForKey(key)

Returns the value for the property specified by key. 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.Important:  You must not override this method.

Parameters:

  • key (String)

    The name of one of the receiver’s properties.

Returns:

  • (Object)

    The value of the property specified by key.

- (Object) willAccessValueForKey(key)

Provides support for key-value observing access notification. 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.

Parameters:

  • key (String)

    The name of one of the receiver's properties.

Returns:

- (Object) willChangeValueForKey(key)

Invoked to inform the receiver that the value of a given property is about to change. For more details, see Key-Value Observing Programming Guide.You must not override this method.

Parameters:

  • key (String)

    The name of the property that will change.

Returns:

- (Object) willChangeValueForKey(inKey, withSetMutation:inMutationKind, usingObjects:inObjects)

Invoked to inform the receiver that the specified change is about to be made to a specified to-many relationship. For more details, see Key-Value Observing Programming Guide.You must not override this method.

Parameters:

  • inKey (String)

    The name of a property that is a to-many relationship

  • inMutationKind (NSKeyValueSetMutationKind)

    The type of change that will be made.

  • inObjects (NSSet)

    The objects that were involved in the change (see NSKeyValueSetMutationKind).

Returns:

- (Object) willSave

Invoked automatically by the Core Data framework when the receiver’s managed object context is saved. 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.

Returns:

- (Object) willTurnIntoFault

Invoked automatically by the Core Data framework before receiver is converted to a fault. 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.

Returns: