Mac Developer Library

Developer

CoreData Framework Reference NSManagedObject Class Reference

Options
Deployment Target:

On This Page
Language:

NSManagedObject

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. More...

Inheritance


Conforms To


Import Statement


import CoreData @import CoreData;

Availability


Available in OS X v10.4 and later.
  • Initializes the receiver and inserts it into the specified managed object context.

    Declaration

    Swift

    init(entity entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?)

    Objective-C

    - (instancetype)initWithEntity:(NSEntityDescription *)entity insertIntoManagedObjectContext:(NSManagedObjectContext *)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;
    • }

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • entity entity Property

    The entity description of the receiver. (read-only)

    Declaration

    Swift

    var entity: NSEntityDescription { get }

    Objective-C

    @property(nonatomic, readonly, strong) NSEntityDescription *entity

    Discussion

    If the receiver is a fault, accessing this property does not cause it to fire.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • objectID objectID Property

    The object ID of the receiver. (read-only)

    Declaration

    Swift

    var objectID: NSManagedObjectID { get }

    Objective-C

    @property(nonatomic, readonly, strong) NSManagedObjectID *objectID

    Discussion

    If the receiver is a fault, accessing this property does not cause it to fire.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

    See Also

    URIRepresentation (NSManagedObjectID)

  • Returns the receiver.

    Declaration

    Objective-C

    - (id)self

    Discussion

    Subclasses must not override this method.

    Note for EOF developers: Core Data does not rely on this method for faulting—see instead willAccessValueForKey:.

    Import Statement

  • The managed object context with which the receiver is registered. (read-only)

    Declaration

    Swift

    unowned(unsafe) var managedObjectContext: NSManagedObjectContext? { get }

    Objective-C

    @property(nonatomic, readonly, assign) NSManagedObjectContext *managedObjectContext

    Discussion

    May be nil if the receiver has been deleted from its context.

    If the receiver is a fault, accessing this property does not cause it to fire.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • A Boolean value that indicates whether the receiver has been inserted, has been deleted, or has unsaved changes. (read-only)

    Declaration

    Swift

    var hasChanges: Bool { get }

    Objective-C

    @property(nonatomic, readonly) BOOL hasChanges

    Discussion

    YEStrue if the receiver has been inserted, has been deleted, or has unsaved changes, otherwise NOfalse. The result is the equivalent of OR-ing the values of inserted, deleted, and updated.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.7 and later.

  • inserted inserted Property

    A Boolean value that indicates whether the receiver has been inserted in a managed object context. (read-only)

    Declaration

    Swift

    var inserted: Bool { get }

    Objective-C

    @property(nonatomic, getter=isInserted, readonly) BOOL inserted

    Discussion

    YEStrue if the receiver has been inserted in a managed object context, otherwise NOfalse. If the receiver is a fault, accessing this property does not cause it to fire.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.10 and later.

  • updated updated Property

    A Boolean value that indicates whether the receiver has unsaved changes. (read-only)

    Declaration

    Swift

    var updated: Bool { get }

    Objective-C

    @property(nonatomic, getter=isUpdated, readonly) BOOL updated

    Discussion

    YEStrue if the receiver has unsaved changes, otherwise NOfalse. The receiver has unsaved changes if it has been updated since its managed object context was last saved.

    If the receiver is a fault, accessing this property does not cause it to fire.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.10 and later.

  • deleted deleted Property

    A Boolean value that indicates whether the receiver will be deleted during the next save. (read-only)

    Declaration

    Swift

    var deleted: Bool { get }

    Objective-C

    @property(nonatomic, getter=isDeleted, readonly) BOOL deleted

    Discussion

    YEStrue if Core Data will ask the persistent store to delete the object during the next save operation, otherwise NOfalse. It may return NOfalse at other times, particularly after the object has been deleted. The immediacy with which it will stop returning YEStrue depends on where the object is in the process of being deleted.

    If the receiver is a fault, accessing this property does not cause it to fire.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.10 and later.

    See Also

    – isFault
    inserted
    updated
    deletedObjects (NSManagedObjectContext)
    NSManagedObjectContextObjectsDidChangeNotification (NSManagedObjectContext)

  • fault fault Property

    A Boolean value that indicates whether the receiver is a fault. (read-only)

    Declaration

    Swift

    var fault: Bool { get }

    Objective-C

    @property(nonatomic, getter=isFault, readonly) BOOL fault

    Discussion

    YEStrue if the receiver is a fault, otherwise NOfalse. 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 property is NOfalse, then the receiver's data must be in memory. However, if this property is YEStrue, it does not mean 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, accessing this property does not cause it to fire.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.10 and later.

  • The faulting state of the receiver. (read-only)

    Declaration

    Swift

    var faultingState: Int { get }

    Objective-C

    @property(nonatomic, readonly) NSUInteger faultingState

    Discussion

    0 if the object is fully initialized as a managed object and not transitioning to or from another state, otherwise some other value. This property allows you to determine if an object is in a transitional phase when receiving a key-value observing change notification.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.5 and later.

    See Also

    fault

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

    Declaration

    Swift

    func hasFaultForRelationshipNamed(_ key: String) -> Bool

    Objective-C

    - (BOOL)hasFaultForRelationshipNamed:(NSString *)key

    Parameters

    key

    The name of one of the receiver’s relationships.

    Return Value

    YEStrue if the relationship for for the key key is a fault, otherwise NOfalse.

    Discussion

    If the specified relationship is a fault, calling this method does not result in the fault firing.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.5 and later.

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

    Declaration

    Swift

    class func contextShouldIgnoreUnmodeledPropertyChanges() -> Bool

    Objective-C

    + (BOOL)contextShouldIgnoreUnmodeledPropertyChanges

    Return Value

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

    Discussion

    The default value is YEStrue.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.6 and later.

    See Also

    – changedValuesForCurrentEvent
    hasChanges (NSManagedObjectContext)

  • Invoked automatically by the Core Data framework after the receiver has been fetched.

    Declaration

    Swift

    func awakeFromFetch()

    Objective-C

    - (void)awakeFromFetch

    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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Invoked automatically by the Core Data framework when the receiver is first inserted into a managed object context.

    Declaration

    Swift

    func awakeFromInsert()

    Objective-C

    - (void)awakeFromInsert

    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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Invoked automatically by the Core Data framework when the receiver is reset due to an undo, redo, or other multi-property state change.

    Declaration

    Swift

    func awakeFromSnapshotEvents(_ flags: NSSnapshotEventType)

    Objective-C

    - (void)awakeFromSnapshotEvents:(NSSnapshotEventType)flags

    Parameters

    flags

    A bit mask 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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.6 and later.

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

    Declaration

    Swift

    func changedValues() -> [NSObject : AnyObject]

    Objective-C

    - (NSDictionary *)changedValues

    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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

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

    Declaration

    Swift

    func changedValuesForCurrentEvent() -> [NSObject : AnyObject]

    Objective-C

    - (NSDictionary *)changedValuesForCurrentEvent

    Return Value

    A dictionary whose keys are the names of persistent properties that have changed since the last posting of NSManagedObjectContextObjectsDidChangeNotification, and whose values are the old value of the persistent 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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.7 and later.

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

    Declaration

    Swift

    func committedValuesForKeys(_ keys: [AnyObject]?) -> [NSObject : AnyObject]

    Objective-C

    - (NSDictionary *)committedValuesForKeys:(NSArray *)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

    nil values are represented by an instance of NSNull.

    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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Invoked automatically by the Core Data framework when the receiver is about to be deleted.

    Declaration

    Swift

    func prepareForDeletion()

    Objective-C

    - (void)prepareForDeletion

    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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.6 and later.

  • Deallocates the memory occupied by the receiver.

    Declaration

    Objective-C

    - (void)dealloc

    Discussion

    This method first invokes didTurnIntoFault.

    You should typically not override this method—instead you should put “clean-up” code in prepareForDeletion or didTurnIntoFault.

    Import Statement

  • Invoked automatically by the Core Data framework when the receiver’s managed object context is saved.

    Declaration

    Swift

    func willSave()

    Objective-C

    - (void)willSave

    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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

    See Also

    – didSave

  • Invoked automatically by the Core Data framework after the receiver’s managed object context completes a save operation.

    Declaration

    Swift

    func didSave()

    Objective-C

    - (void)didSave

    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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

    See Also

    – willSave

  • Invoked automatically by the Core Data framework before receiver is converted to a fault.

    Declaration

    Swift

    func willTurnIntoFault()

    Objective-C

    - (void)willTurnIntoFault

    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 key paths). The default implementation does nothing.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.5 and later.

  • Invoked automatically by the Core Data framework when the receiver is turned into a fault.

    Declaration

    Swift

    func didTurnIntoFault()

    Objective-C

    - (void)didTurnIntoFault

    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:).

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Returns the value for the property specified by key.

    Declaration

    Swift

    func valueForKey(_ key: String) -> AnyObject?

    Objective-C

    - (id)valueForKey:(NSString *)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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Sets the specified property of the receiver to the specified value.

    Declaration

    Swift

    func setValue(_ value: AnyObject?, forKey key: String)

    Objective-C

    - (void)setValue:(id)value forKey:(NSString *)key

    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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

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

    Declaration

    Objective-C

    - (NSMutableSet *)mutableSetValueForKey:(NSString *)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).

    Import Statement

  • Returns from the receiver’s private internal storage the value for the specified property.

    Declaration

    Swift

    func primitiveValueForKey(_ key: String) -> AnyObject?

    Objective-C

    - (id)primitiveValueForKey:(NSString *)key

    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 of primitiveValueForKey:@"name"). The dynamic accessors are much more efficient, and allow for compile-time checking.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Sets in the receiver's private internal storage the value of a given property.

    Declaration

    Swift

    func setPrimitiveValue(_ value: AnyObject?, forKey key: String)

    Objective-C

    - (void)setPrimitiveValue:(id)value forKey:(NSString *)key

    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 in Core Data Programming Guide.

    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 of setPrimitiveValue:newName forKey:@"name"). The dynamic accessors are much more efficient, and allow for compile-time checking.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Validates a property value for a given key.

    Declaration

    Swift

    func validateValue(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>, forKey key: String, error error: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)validateValue:(id *)value forKey:(NSString *)key error:(NSError **)error

    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 NSError that describes the problem.

    Return Value

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

    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 NOfalse and in error an NSError object that describes the problem. For more details, see Managed Object Validation in Core Data Programming Guide. For inter-property validation (to check for combinations of values that are invalid), see validateForUpdate: and related methods.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Determines whether the receiver can be deleted in its current state.

    Declaration

    Swift

    func validateForDelete(_ error: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)validateForDelete:(NSError **)error

    Parameters

    error

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

    Return Value

    YEStrue if the receiver can be deleted in its current state, otherwise NOfalse.

    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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

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

    Declaration

    Swift

    func validateForInsert(_ error: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)validateForInsert:(NSError **)error

    Parameters

    error

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

    Return Value

    YEStrue if the receiver can be inserted in its current state, otherwise NOfalse.

    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 Managed Object Validation in Core Data Programming Guide).

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Determines whether the receiver’s current state is valid.

    Declaration

    Swift

    func validateForUpdate(_ error: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)validateForUpdate:(NSError **)error

    Parameters

    error

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

    Return Value

    YEStrue if the receiver's current state is valid, otherwise NOfalse.

    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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

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

    Declaration

    Objective-C

    + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key

    Parameters

    key

    The name of one of the receiver's properties.

    Return Value

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

    Discussion

    The default implementation for NSManagedObject returns NOfalse for modeled properties, and YEStrue for unmodeled properties. For more about key-value observation, see Key-Value Observing Programming Guide.

    Import Statement

  • Provides support for key-value observing access notification.

    Declaration

    Swift

    func didAccessValueForKey(_ key: String)

    Objective-C

    - (void)didAccessValueForKey:(NSString *)key

    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;
    • }

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Returns the observation info of the receiver.

    Declaration

    Swift

    func observationInfo() -> AnyObject?

    Objective-C

    - (id)observationInfo

    Return Value

    The observation info of the receiver.

    Discussion

    For more about key-value observation, see Key-Value Observing Programming Guide.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Sets the observation info of the receiver.

    Declaration

    Swift

    func setObservationInfo(_ value: AnyObject?)

    Objective-C

    - (void)setObservationInfo:(id)value

    Parameters

    value

    The new observation info for the receiver.

    Discussion

    For more about observation information, see Key-Value Observing Programming Guide.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Provides support for key-value observing access notification.

    Declaration

    Swift

    func willAccessValueForKey(_ key: String?)

    Objective-C

    - (void)willAccessValueForKey:(NSString *)key

    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];

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Invoked to inform the receiver that the value of a given property has changed.

    Declaration

    Swift

    func didChangeValueForKey(_ key: String)

    Objective-C

    - (void)didChangeValueForKey:(NSString *)key

    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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Invoked to inform the receiver that the specified change was made to a specified to-many relationship.

    Declaration

    Swift

    func didChangeValueForKey(_ inKey: String, withSetMutation inMutationKind: NSKeyValueSetMutationKind, usingObjects inObjects: NSSet)

    Objective-C

    - (void)didChangeValueForKey:(NSString *)inKey withSetMutation:(NSKeyValueSetMutationKind)inMutationKind usingObjects:(NSSet *)inObjects

    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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Invoked to inform the receiver that the value of a given property is about to change.

    Declaration

    Swift

    func willChangeValueForKey(_ key: String)

    Objective-C

    - (void)willChangeValueForKey:(NSString *)key

    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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Invoked to inform the receiver that the specified change is about to be made to a specified to-many relationship.

    Declaration

    Swift

    func willChangeValueForKey(_ inKey: String, withSetMutation inMutationKind: NSKeyValueSetMutationKind, usingObjects inObjects: NSSet)

    Objective-C

    - (void)willChangeValueForKey:(NSString *)inKey withSetMutation:(NSKeyValueSetMutationKind)inMutationKind usingObjects:(NSSet *)inObjects

    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.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.4 and later.

  • Constants returned from awakeFromSnapshotEvents: to denote the reason why a managed object may need to reinitialize values.

    Declaration

    Swift

    struct NSSnapshotEventType : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var UndoInsertion: NSSnapshotEventType { get } static var UndoDeletion: NSSnapshotEventType { get } static var UndoUpdate: NSSnapshotEventType { get } static var Rollback: NSSnapshotEventType { get } static var Refresh: NSSnapshotEventType { get } static var MergePolicy: NSSnapshotEventType { get } }

    Objective-C

    enum { NSSnapshotEventUndoInsertion = 1 << 1, NSSnapshotEventUndoDeletion = 1 << 2, NSSnapshotEventUndoUpdate = 1 << 3, NSSnapshotEventRollback = 1 << 4, NSSnapshotEventRefresh = 1 << 5, NSSnapshotEventMergePolicy = 1 << 6 }; typedef NSUInteger NSSnapshotEventType;

    Constants

    • UndoInsertion

      NSSnapshotEventUndoInsertion

      Specifies a change due to undo from insertion.

      Available in OS X v10.6 and later.

    • UndoDeletion

      NSSnapshotEventUndoDeletion

      Specifies a change due to undo from deletion.

      Available in OS X v10.6 and later.

    • UndoUpdate

      NSSnapshotEventUndoUpdate

      Specifies a change due to a property-level undo.

      Available in OS X v10.6 and later.

    • Rollback

      NSSnapshotEventRollback

      Specifies a change due to the managed object context being rolled back.

      Available in OS X v10.6 and later.

    • Refresh

      NSSnapshotEventRefresh

      Specifies a change due to the managed object being refreshed.

      Available in OS X v10.6 and later.

    • MergePolicy

      NSSnapshotEventMergePolicy

      Specifies a change due to conflict resolution during a save operation.

      Available in OS X v10.6 and later.

    Import Statement

    import CoreData

    Availability

    Available in OS X v10.6 and later.