CoreData ObjC PDF
CoreData ObjC PDF
Contents
Contents
NSExpressionDescription 86
Overview 86 Tasks 86 Instance Methods 87
Contents
Overview 142 Tasks 146 Class Methods 150 Instance Methods 151 Constants 180
Contents
Constants 335
Contents
Tables
/System/Library/Frameworks/CoreData.framework /System/Library/Frameworks/CoreData.framework/Headers CoreDataDefines.h CoreDataErrors.h NSAtomicStore.h NSAtomicStoreCacheNode.h NSAttributeDescription.h NSEntityDescription.h NSEntityMapping.h NSEntityMigrationPolicy.h NSExpressionDescription.h NSFetchRequest.h NSFetchRequestExpression.h NSFetchedPropertyDescription.h NSIncrementalStore.h NSIncrementalStoreNode.h NSManagedObject.h NSManagedObjectContext.h NSManagedObjectID.h NSManagedObjectModel.h NSMappingModel.h NSMergePolicy.h NSPersistentStore.h NSPersistentStoreCoordinator.h NSPersistentStoreRequest.h NSPropertyDescription.h NSPropertyMapping.h NSRelationshipDescription.h
This collection of documents provides the API reference for the Core Data framework. Core Data provides object graph management and persistence for Foundation and Cocoa applications. For more details, see Core Data Basics.
Classes
10
NSPersistentStore : NSObject NSObject (NSObject) /System/Library/Frameworks/CoreData.framework Available in OS X v10.5 and later. NSAtomicStore.h Atomic Store Programming Topics Core Data Programming Guide
Overview
NSAtomicStore is an abstract superclass that you can subclass to create a Core Data atomic store. It provides
default implementations of some utility methods. You use a custom atomic store if you have a custom file format that you want to integrate with a Core Data application. The atomic stores are all intended to handle data sets that can be expressed in memory. The atomic store API favors simplicity over performance.
Subclassing Notes
Methods to Override
In a subclass of NSAtomicStore, you must override the following methods to provide behavior appropriate for your store:
load: (page 16) newReferenceObjectForManagedObject: (page 18) save: (page 20)
Loads the cache nodes for the receiver. Returns a new reference object for a given managed object. Saves the cache nodes.
11
Updates the given cache node using the values in a given managed object.
These are in addition to the methods you must override for a subclass of NSPersistentStore:
type (page 270) identifier (page 264)
Returns the type string of the receiver. Returns the unique identifier for the receiver. Sets the unique identifier for the receiver. Returns the metadata for the receiver. Returns the metadata from the persistent store at the given URL. Sets the metadata for the store at a given URL.
setIdentifier: (page 268) metadata (page 267) metadataForPersistentStoreWithURL:error: (page 261) setMetadata:forPersistentStoreWithURL:error: (page 263)
Tasks
Initializing a Store
initWithPersistentStoreCoordinator:configurationName:URL:options:
(page 15)
Loading a Store
load:
(page 16) Loads the cache nodes for the receiver. (page 19) Returns a managed object ID from the reference data for a specified entity. (page 14) Registers a set of cache nodes with the receiver.
objectIDForEntity:referenceObject:
addCacheNodes:
12
(page 18) Returns a new cache node for a given managed object. (page 18) Returns a new reference object for a given managed object. (page 21) Updates the given cache node using the values in a given managed object. (page 22) Method invoked before the store removes the given collection of cache nodes.
newReferenceObjectForManagedObject:
updateCacheNode:fromManagedObject:
willRemoveCacheNodes:
Saving a Store
save:
Utility Methods
cacheNodes
(page 15) Returns the set of cache nodes registered with the receiver. (page 14) Returns the cache node for a given managed object ID. (page 20) Returns the reference object for a given managed object ID.
cacheNodeForObjectID:
referenceObjectForObjectID:
Managing Metadata
metadata
(page 17) Returns the metadata for the receiver. (page 21) Sets the metadata for the receiver.
setMetadata:
13
Instance Methods
addCacheNodes:
Registers a set of cache nodes with the receiver.
- (void)addCacheNodes:(NSSet *)cacheNodes
Parameters
cacheNodes
A set of cache nodes. Discussion You should invoke this method in a subclass during the call to load: (page 16) to register the loaded information with the store. Availability Available in OS X v10.5 and later. Declared in
NSAtomicStore.h
cacheNodeForObjectID:
Returns the cache node for a given managed object ID.
- (NSAtomicStoreCacheNode *)cacheNodeForObjectID:(NSManagedObjectID *)objectID
Parameters
objectID
A managed object ID. Return Value The cache node for objectID. Discussion This method is normally used by cache nodes to locate related cache nodes (by relationships). Availability Available in OS X v10.5 and later. Declared in
NSAtomicStore.h
14
cacheNodes
Returns the set of cache nodes registered with the receiver.
- (NSSet *)cacheNodes
Return Value The set of cache nodes registered with the receiver. Discussion You should modify this collection using addCacheNodes: (page 14): and willRemoveCacheNodes: (page 22). Availability Available in OS X v10.5 and later. Declared in
NSAtomicStore.h
initWithPersistentStoreCoordinator:configurationName:URL:options:
Returns an atomic store, initialized with the given arguments.
- (id)initWithPersistentStoreCoordinator:(NSPersistentStoreCoordinator *)coordinator
Parameters
coordinator
The URL of the store to load. This value must not be nil.
options
A dictionary containing configuration options. Return Value An atomic store, initialized with the given arguments, or nil if the store could not be initialized.
15
Discussion You typically do not invoke this method yourself; it is invoked by the persistent store coordinator during addPersistentStoreWithType:configuration:URL:options:error: (page 279), both when a new store is created and when an existing store is opened. In your implementation, you should check whether a file already exists at url; if it does not, then you should either create a file here or ensure that your load: (page 16) method does not fail if the file does not exist. Any subclass of NSAtomicStore must be able to handle being initialized with a URL pointing to a zero-length file. This serves as an indicator that a new store is to be constructed at the specified location and allows you to securely create reservation files in known locations which can then be passed to Core Data to construct stores. You may choose to create zero-length reservation files during initWithPersistentStoreCoordinator:configurationName:URL:options: or load: (page 16). If you do so, you must remove the reservation file if the store is removed from the coordinator before it is saved. You should ensure that you load metadata during initialization and set it using setMetadata: (page 21). Special Considerations You must invoke supers implementation to ensure that the store is correctly initialized. Availability Available in OS X v10.5 and later. See Also load: (page 16) setMetadata: (page 21) Declared in
NSAtomicStore.h
load:
Loads the cache nodes for the receiver.
- (BOOL)load:(NSError **)error
Parameters
error
If an error occurs, upon return contains an NSError object that describes the problem. Return Value YES if the cache nodes were loaded correctly, otherwise NO.
16
Discussion You override this method to to load the data from the URL specified in
initWithPersistentStoreCoordinator:configurationName:URL:options: (page 15) and create cache nodes
for the represented objects. You must respect the configuration specified for the store, as well as the options. Any subclass of NSAtomicStore must be able to handle being initialized with a URL pointing to a zero-length file. This serves as an indicator that a new store is to be constructed at the specified location and allows you to securely create reservation files in known locations which can then be passed to Core Data to construct stores. You may choose to create zero-length reservation files during initWithPersistentStoreCoordinator:configurationName:URL:options: (page 15) or load:. If you do so, you must remove the reservation file if the store is removed from the coordinator before it is saved. Special Considerations You must override this method. Availability Available in OS X v10.5 and later. See Also
addCacheNodes:
(page 14)
Declared in
NSAtomicStore.h
metadata
Returns the metadata for the receiver.
- (NSDictionary *)metadata
(NSStoreTypeKey (page 292) and NSStoreUUIDKey (page 292)) as well as store versioning information. Subclasses must ensure that the metadata is saved along with the store data. See Also
metadata (page 267) (NSPersistentStore)
17
newCacheNodeForManagedObject:
Returns a new cache node for a given managed object.
- (NSAtomicStoreCacheNode *)newCacheNodeForManagedObject:(NSManagedObject
*)managedObject
Parameters
managedObject
A managed object. Return Value A new cache node for managedObject. Discussion This method is invoked by the framework after a save operation on a managed object content, once for each newly-inserted NSManagedObject instance.
NSAtomicStore provides a default implementation that returns a suitable cache node. You can override this
method to take the information from the managed object and return a custom cache node. Availability Available in OS X v10.5 and later. Declared in
NSAtomicStore.h
newReferenceObjectForManagedObject:
Returns a new reference object for a given managed object.
- (id)newReferenceObjectForManagedObject:(NSManagedObject *)managedObject
Parameters
managedObject
A managed object. At the time this method is called, it has a temporary ID. Return Value A new reference object for managedObject.
18
Discussion This method is invoked by the framework after a save operation on a managed object context, once for each newly-inserted managed object. The value returned is used to create a permanent ID for the object and must be unique for an instance within its entity's inheritance hierarchy (in this store). Special Considerations You must override this method. This method must return a stable (unchanging) value for a given object, otherwise Save As and migration will not work correctly. This means that you can use arbitrary numbers, UUIDs, or other random values only if they are persisted with the raw data. If you cannot save the originally-assigned reference object with the data, then the method must derive the reference object from the managed objects values. For more details, see Atomic Store Programming Topics . Availability Available in OS X v10.5 and later. Declared in
NSAtomicStore.h
objectIDForEntity:referenceObject:
Returns a managed object ID from the reference data for a specified entity.
- (NSManagedObjectID *)objectIDForEntity:(NSEntityDescription *)entity
referenceObject:(id)data
Parameters
entity
Reference data for which the managed object ID is required. Return Value The managed object ID from the reference data for a specified entity Discussion You use this method to create managed object IDs which are then used to create cache nodes for information being loaded into the store. Special Considerations You should not override this method.
19
(page 14)
Declared in
NSAtomicStore.h
referenceObjectForObjectID:
Returns the reference object for a given managed object ID.
- (id)referenceObjectForObjectID:(NSManagedObjectID *)objectID
Parameters
objectID
A managed object ID. Return Value The reference object for objectID. Discussion Subclasses should invoke this method to extract the reference data from the object ID for each cache node if the data is to be made persistent. Availability Available in OS X v10.5 and later. Declared in
NSAtomicStore.h
save:
Saves the cache nodes.
- (BOOL)save:(NSError **)error
Parameters
error
If an error occurs, upon return contains an NSError object that describes the problem.
20
Discussion You override this method to make persistent the necessary information from the cache nodes to the URL specified for the receiver. Special Considerations You must override this method. Availability Available in OS X v10.5 and later. See Also
newReferenceObjectForManagedObject: updateCacheNode:fromManagedObject: willRemoveCacheNodes:
(page 22)
Declared in
NSAtomicStore.h
setMetadata:
Sets the metadata for the receiver.
- (void)setMetadata:(NSDictionary *)storeMetadata
Parameters
storeMetadata
(page 17)
updateCacheNode:fromManagedObject:
Updates the given cache node using the values in a given managed object.
- (void)updateCacheNode:(NSAtomicStoreCacheNode *)node
fromManagedObject:(NSManagedObject *)managedObject
Parameters
node
21
managedObject
The managed object with which to update node. Discussion This method is invoked by the framework after a save operation on a managed object context, once for each updated NSManagedObject instance. You override this method in a subclass to take the information from managedObject and update node. Special Considerations You must override this method. Availability Available in OS X v10.5 and later. Declared in
NSAtomicStore.h
willRemoveCacheNodes:
Method invoked before the store removes the given collection of cache nodes.
- (void)willRemoveCacheNodes:(NSSet *)cacheNodes
Parameters
cacheNodes
The set of cache nodes to remove. Discussion This method is invoked by the store before the call to save: (page 20) with the collection of cache nodes marked as deleted by a managed object context. You can override this method to track the nodes which will not be made persistent in the save: (page 20) method. You should not invoke this method directly in a subclass. Availability Available in OS X v10.5 and later. See Also save: (page 20) Declared in
NSAtomicStore.h
22
NSObject NSObject (NSObject) /System/Library/Frameworks/CoreData.framework Available in OS X v10.5 and later. NSAtomicStoreCacheNode.h Core Data Programming Guide
Overview
NSAtomicStoreCacheNode is a concrete class to represent basic nodes in a Core Data atomic store.
A node represents a single record in a persistent store. You can subclass NSAtomicStoreCacheNode to provide custom behavior.
Tasks
Designated Initializer
initWithObjectID:
(page 24) Returns a cache node for the given managed object ID.
Node Data
objectID
23
propertyCache
(page 25) Returns the property cache dictionary for the receiver. (page 25) Sets the property cache dictionary for the receiver. (page 26) Returns the value for a given key. (page 26) Sets the value for the given key.
setPropertyCache:
valueForKey:
setValue:forKey:
Instance Methods
initWithObjectID:
Returns a cache node for the given managed object ID.
- (id)initWithObjectID:(NSManagedObjectID *)moid
Parameters
moid
A managed object ID. Return Value A cache node for the given managed object ID, or nil if the node could not be initialized. Availability Available in OS X v10.5 and later. Declared in
NSAtomicStoreCacheNode.h
objectID
Returns the managed object ID for the receiver.
- (NSManagedObjectID *)objectID
24
propertyCache
Returns the property cache dictionary for the receiver.
- (NSMutableDictionary *)propertyCache
Return Value The property cache dictionary for the receiver. Discussion This dictionary is used by valueForKey: (page 26) and setValue:forKey: (page 26) for property values. The default implementation returns nil unless the companion -setPropertyCache: method is invoked, or setValue:forKey: is invoked on the cache node with non-nil property values. Availability Available in OS X v10.5 and later. Declared in
NSAtomicStoreCacheNode.h
setPropertyCache:
Sets the property cache dictionary for the receiver.
- (void)setPropertyCache:(NSMutableDictionary *)propertyCache
Parameters
propertyCache
The property cache dictionary for the receiver. Availability Available in OS X v10.5 and later. Declared in
NSAtomicStoreCacheNode.h
25
setValue:forKey:
Sets the value for the given key.
- (void)setValue:(id)value forKey:(NSString *)key
Parameters
value
The name of a property. Discussion The default implementation forwards the request to the propertyCache (page 25) dictionary if key matches a property name of the entity for this cache node. If key does not represent a property, the standard setValue:forKey: implementation is used. Availability Available in OS X v10.5 and later. Declared in
NSAtomicStoreCacheNode.h
valueForKey:
Returns the value for a given key.
- (id)valueForKey:(NSString *)key
Parameters
key
The name of a property. Return Value The value for the property named key. For an attribute, the return value is an instance of an attribute type supported by Core Data (see NSAttributeDescription); for a to-one relationship, the return value must be another cache node instance; for a to-many relationship, the return value must be an collection of the related cache nodes.
26
Discussion The default implementation forwards the request to the propertyCache (page 25) dictionary if key matches a property name of the entity for the cache node. If key does not represent a property, the standard valueForKey: implementation is used. Availability Available in OS X v10.5 and later. Declared in
NSAtomicStoreCacheNode.h
27
/System/Library/Frameworks/CoreData.framework Available in OS X v10.4 and later. NSAttributeDescription.h Core Data Programming Guide Core Data Utility Tutorial
Overview
The NSAttributeDescription class is used to describe attributes of an entity described by an instance of NSEntityDescription.
NSAttributeDescription inherits from NSPropertyDescription, which provides most of the basic
behavior. Instances of NSAttributeDescription are used to describe attributes, as distinct from relationships. The class adds the ability to specify the attribute type, and to specify a default value. In a managed object model, you must specify the type of all attributesyou can only use the undefined attribute type (NSUndefinedAttributeType) for transient attributes.
28
enforced at runtime: any attempt to mutate a model or any of its sub-objects after the model is associated with a persistent store coordinator causes an exception to be thrown. If you need to modify a model that is in use, create a copy, modify the copy, and then discard the objects with the old model. Note: Default values set for attributes are retained by a managed object model, not copied. This means that attribute values do not have to implement the NSCopying protocol, however it also means that you should not modify any objects after they have been set as default values.
Tasks
Getting and Setting Type Information
attributeType
(page 31) Returns the type of the receiver. (page 32) Sets the type of the receiver. (page 31) Returns the name of the class used to represent the receiver. (page 33) Sets the name of the class used to represent the receiver.
setAttributeType:
attributeValueClassName
setAttributeValueClassName:
(page 31) Returns the default value of the receiver. (page 33) Sets the default value of the receiver.
setDefaultValue:
Versioning Support
versionHash
29
Value Transformers
valueTransformerName
(page 35) Returns the name of the transformer used to transform the attribute value. (page 34) Sets the name of the transformer to use to transform the attribute value.
setValueTransformerName:
(page 30) Returns a Boolean value that indicates whether the attribute allows external binary storage. (page 32) Sets whether the atribute allows
setAllowsExternalBinaryDataStorage:
Instance Methods
allowsExternalBinaryDataStorage
Returns a Boolean value that indicates whether the attribute allows external binary storage.
- (BOOL)allowsExternalBinaryDataStorage
Return Value YES if the attribute allows external binary storage, otherwise NO. Discussion If this value is YES, the corresponding attribute may be stored in a file external to the persistent store itself. Availability Available in OS X v10.7 and later. See Also
setAllowsExternalBinaryDataStorage:
(page 32)
Declared in
NSAttributeDescription.h
30
attributeType
Returns the type of the receiver.
- (NSAttributeType)attributeType
Return Value The type of the receiver. Availability Available in OS X v10.4 and later. See Also (page 31) setAttributeType: (page 32)
attributeValueClassName
Declared in
NSAttributeDescription.h
attributeValueClassName
Returns the name of the class used to represent the receiver.
- (NSString *)attributeValueClassName
Return Value The name of the class used to represent the receiver, as a string. Availability Available in OS X v10.4 and later. See Also (page 31) setAttributeType: (page 32)
attributeType
Declared in
NSAttributeDescription.h
defaultValue
Returns the default value of the receiver.
- (id)defaultValue
31
Return Value The default value of the receiver. Availability Available in OS X v10.4 and later. See Also
setDefaultValue:
(page 33)
Declared in
NSAttributeDescription.h
setAllowsExternalBinaryDataStorage:
Sets whether the atribute allows
- (void)setAllowsExternalBinaryDataStorage:(BOOL)flag
Parameters
flag
A Boolean value that indicates whether the attribute should allow external binary storage. Availability Available in OS X v10.7 and later. See Also
allowsExternalBinaryDataStorage
(page 30)
Declared in
NSAttributeDescription.h
setAttributeType:
Sets the type of the receiver.
- (void)setAttributeType:(NSAttributeType)type
Parameters
type
32
Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also
attributeType
attributeValueClassName
Declared in
NSAttributeDescription.h
setAttributeValueClassName:
Sets the name of the class used to represent the receiver.
- (void)setAttributeValueClassName:(NSString *)className
Parameters
className
The name of the class used to represent the receiver. Discussion If you set the value class name, Core Data can check the class of any instance set as the value of an attribute. Availability Available in OS X v10.5 and later. See Also
attributeValueClassName
(page 31)
Declared in
NSAttributeDescription.h
setDefaultValue:
Sets the default value of the receiver.
- (void)setDefaultValue:(id)value
33
Parameters
value
The default value for the receiver. Discussion Default values are retained by a managed object model, not copied. This means that attribute values do not have to implement the NSCopying protocol, however it also means that you should not modify any objects after they have been set as default values. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also
defaultValue
(page 31)
Declared in
NSAttributeDescription.h
setValueTransformerName:
Sets the name of the transformer to use to transform the attribute value.
- (void)setValueTransformerName:(NSString *)string
Parameters
string
The name of the transformer to use to transform the attribute value. The transformer must output an NSData object from transformedValue: and must allow reverse transformations. Discussion The receiver must be an attribute of type NSTransformedAttributeType. If this value is not set, or is set to nil, Core Data will default to using a transformer which uses NSCoding to archive and unarchive the attribute value. Availability Available in OS X v10.5 and later.
34
See Also
valueTransformerName
(page 35)
Declared in
NSAttributeDescription.h
valueTransformerName
Returns the name of the transformer used to transform the attribute value.
- (NSString *)valueTransformerName
Return Value The name of the transformer used to transform the attribute value. Discussion The receiver must be an attribute of type NSTransformedAttributeType. Availability Available in OS X v10.5 and later. See Also
setValueTransformerName:
(page 34)
Declared in
NSAttributeDescription.h
versionHash
Returns the version hash for the receiver.
- (NSData *)versionHash
Return Value The version hash for the receiver. Discussion The version hash is used to uniquely identify an attribute based on its configuration. This value includes the versionHash (page 317) information from NSPropertyDescription and the attribute type. Availability Available in OS X v10.5 and later.
35
See Also
versionHash (page 317) (NSPropertyDescription)
Declared in
NSAttributeDescription.h
Constants
NSAttributeType
Defines the possible types of NSAttributeType properties. These explicitly distinguish between bit sizes to ensure data store independence.
typedef enum { NSUndefinedAttributeType = 0, NSInteger16AttributeType = 100, NSInteger32AttributeType = 200, NSInteger64AttributeType = 300, NSDecimalAttributeType = 400, NSDoubleAttributeType = 500, NSFloatAttributeType = 600, NSStringAttributeType = 700, NSBooleanAttributeType = 800, NSDateAttributeType = 900, NSBinaryDataAttributeType = 1000, NSTransformableAttributeType = 1800, NSObjectIDAttributeType = 2000 } NSAttributeType;
Constants
NSUndefinedAttributeType
as an id value and register undo/redo actions, and so on. NSUndefinedAttributeType is illegal for non-transient properties. Available in OS X v10.4 and later. Declared in NSAttributeDescription.h.
36
NSInteger16AttributeType
Specifies a 16-bit signed integer attribute. Available in OS X v10.4 and later. Declared in NSAttributeDescription.h.
NSInteger32AttributeType
Specifies a 32-bit signed integer attribute. Available in OS X v10.4 and later. Declared in NSAttributeDescription.h.
NSInteger64AttributeType
Specifies a 64-bit signed integer attribute. Available in OS X v10.4 and later. Declared in NSAttributeDescription.h.
NSDecimalAttributeType
37
NSDateAttributeType
Specifies an NSDate attribute. Times are specified in GMT. Available in OS X v10.4 and later. Declared in NSAttributeDescription.h.
NSBinaryDataAttributeType
Specifies an attribute that uses a value transformer. Available in OS X v10.5 and later. Declared in NSAttributeDescription.h.
NSObjectIDAttributeType
Specifies the object ID attribute. Available in OS X v10.6 and later. Declared in NSAttributeDescription.h. Availability Available in OS X v10.4 and later. Declared in
NSAttributeDescription.h
38
/System/Library/Frameworks/CoreData.framework Available in OS X v10.4 and later. CoreData/NSEntityDescription.h Core Data Programming Guide Core Data Utility Tutorial
Overview
An NSEntityDescription object describes an entity in Core Data. Entities are to managed objects what Class is to id, orto use a database analogywhat tables are to rows. An instance specifies an entitys name, its properties (its attributes and relationships, expressed by instances of NSAttributeDescription and NSRelationshipDescription) and the class by which it is represented. An NSEntityDescription object is associated with a specific class whose instances are used to represent entries in a persistent store in applications using the Core Data Framework. Minimally, an entity description should have:
A name The name of a managed object class (If an entity has no managed object class name, it defaults to NSManagedObject.)
39
You usually define entities in a managed object modelusing the data modeling tool in Xcode. NSEntityDescription objects are primarily used by the Core Data Framework for mapping entries in the persistent store to managed objects in the application. You are not likely to interact with them directly unless you are specifically working with models. Like the other major modeling classes, NSEntityDescription provides you with a user dictionary in which you can store any application-specific information related to the entity.
Since NSDictionary copies its keys and requires that keys both conform to the NSCopying protocol and have the property that copy returns an object for which [[object copy] isEqual:object] is true, you should not use entities as keys in a dictionary. Instead, you should either use the entitys name as the key, or use a map table (NSMapTable) with retain callbacks.
Fast Enumeration
NSEntityDescription supports the NSFastEnumeration protocol. You can use this to enumerate over
40
Tasks
Information About an Entity Description
name
(page 49) Returns the entity name of the receiver. (page 54) Sets the entity name of the receiver. (page 48) Returns the managed object model with which the receiver is associated. (page 48) Returns the name of the class that represents the receivers entity. (page 53) Sets the name of the class that represents the receivers entity. (page 51) Returns the renaming identifier for the receiver. (page 55) Sets the renaming identifier for the receiver. (page 47) Returns a Boolean value that indicates whether the receiver represents an abstract entity. (page 52) Sets whether the receiver represents an abstract entity. (page 59) Returns the user info dictionary of the receiver. (page 56) Sets the user info dictionary of the receiver.
setName:
managedObjectModel
managedObjectClassName
setManagedObjectClassName:
renamingIdentifier
setRenamingIdentifier:
isAbstract
setAbstract:
userInfo
setUserInfo:
41
Managing Inheritance
subentitiesByName
(page 58) Returns the sub-entities of the receiver in a dictionary. (page 57) Returns an array containing the sub-entities of the receiver. (page 55) Sets the subentities of the receiver. (page 58) Returns the super-entity of the receiver. (page 47) Returns a Boolean value that indicates whether the receiver is a sub-entity of another given entity.
subentities
setSubentities:
superentity
isKindOfEntity:
(page 50) Returns a dictionary containing the properties of the receiver. (page 49) Returns an array containing the properties of the receiver. (page 54) Sets the properties array of the receiver. (page 45) Returns the attributes of the receiver in a dictionary, where the keys in the dictionary are the attribute names. (page 50) Returns the relationships of the receiver in a dictionary, where the keys in the dictionary are the relationship names. (page 51) Returns an array containing the relationships of the receiver where the entity description of the relationship is a given entity.
properties
setProperties:
attributesByName
relationshipsByName
relationshipsWithDestinationEntity:
42
(page 44) Returns the entity with the specified name from the managed object model associated with the specified managed object contexts persistent store coordinator.
(page 44) Creates, configures, and returns an instance of the class for the entity with a given name.
(page 59) Returns the version hash for the receiver. (page 60) Returns the version hash modifier for the receiver. (page 57) Sets the version hash modifier for the receiver.
versionHashModifier
setVersionHashModifier:
(page 46) Returns the compound indexes for the entity as an array of arrays. (page 52) Sets the compound indexes for the entity as an array of arrays.
setCompoundIndexes:
43
Class Methods
entityForName:inManagedObjectContext:
Returns the entity with the specified name from the managed object model associated with the specified managed object contexts persistent store coordinator.
+ (NSEntityDescription *)entityForName:(NSString *)entityName
inManagedObjectContext:(NSManagedObjectContext *)context
Parameters
entityName
The managed object context to use. Return Value The entity with the specified name from the managed object model associated with contexts persistent store coordinator. Discussion This method is functionally equivalent to the following code example.
NSManagedObjectModel *managedObjectModel = [[context persistentStoreCoordinator] managedObjectModel]; NSEntityDescription *entity = [[managedObjectModel entitiesByName] objectForKey:entityName]; return entity;
(page 232)
Declared in
NSEntityDescription.h
insertNewObjectForEntityForName:inManagedObjectContext:
Creates, configures, and returns an instance of the class for the entity with a given name.
44
+ (id)insertNewObjectForEntityForName:(NSString *)entityName
inManagedObjectContext:(NSManagedObjectContext *)context
Parameters
entityName
The managed object context to use. Return Value A new, autoreleased, fully configured instance of the class for the entity named entityName. The instance has its entity description set and is inserted it into context. Discussion This method makes it easy for you to create instances of a given entity without worrying about the details of managed object creation. The method is conceptually similar to the following code example.
NSManagedObjectModel *managedObjectModel = [[context persistentStoreCoordinator] managedObjectModel]; NSEntityDescription *entity = [[managedObjectModel entitiesByName] objectForKey:entityName]; NSManagedObject *newObject = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:context]; return newObject;
(page 161)
Declared in
NSEntityDescription.h
Instance Methods
attributesByName
Returns the attributes of the receiver in a dictionary, where the keys in the dictionary are the attribute names.
45
- (NSDictionary *)attributesByName
Return Value The attributes of the receiver in a dictionary, where the keys in the dictionary are the attribute names and the values are instances of NSAttributeDescription. . Availability Available in OS X v10.4 and later. See Also (page 50) relationshipsByName (page 50)
propertiesByName relationshipsWithDestinationEntity:
(page 51)
Declared in
NSEntityDescription.h
compoundIndexes
Returns the compound indexes for the entity as an array of arrays.
- (NSArray *)compoundIndexes
Return Value An array of arrays. The arrays contained in the returned array contain instances of NSAttributeDescription, NSRelationshipDescription that represent properties of the entity, or of NSString that match the name of attributes or relationships of the entity. Discussion Availability Available in OS X v10.8 and later. See Also
setCompoundIndexes:
(page 52)
Declared in
NSEntityDescription.h
46
copy
Returns a copy of the receiver
- (id)copy
You should not, therefore, use an entity as a key in a dictionary (see Using Entity Descriptions in Dictionaries (page 40)).
isAbstract
Returns a Boolean value that indicates whether the receiver represents an abstract entity.
- (BOOL)isAbstract
Return Value YES if the receiver represents an abstract entity, otherwise NO. Discussion An abstract entity might be Shape, with concrete sub-entities such as Rectangle, Triangle, and Circle. Availability Available in OS X v10.4 and later. See Also
setAbstract:
(page 52)
Declared in
NSEntityDescription.h
isKindOfEntity:
Returns a Boolean value that indicates whether the receiver is a sub-entity of another given entity.
- (BOOL)isKindOfEntity:(NSEntityDescription *)entity
47
Parameters
entity
An entity. Return Value YES if the receiver is a sub-entity of entity, otherwise NO. Availability Available in OS X v10.5 and later. Declared in
NSEntityDescription.h
managedObjectClassName
Returns the name of the class that represents the receivers entity.
- (NSString *)managedObjectClassName
Return Value The name of the class that represents the receivers entity. Availability Available in OS X v10.4 and later. See Also
setManagedObjectClassName:
(page 53)
Declared in
NSEntityDescription.h
managedObjectModel
Returns the managed object model with which the receiver is associated.
- (NSManagedObjectModel *)managedObjectModel
Return Value The managed object model with which the receiver is associated. Availability Available in OS X v10.4 and later.
48
See Also
setEntities: (page 238) (NSManagedObjectModel) setEntities:forConfiguration: (page 238): (NSManagedObjectModel)
Declared in
NSEntityDescription.h
name
Returns the entity name of the receiver.
- (NSString *)name
Return Value The entity name of receiver. Availability Available in OS X v10.4 and later. See Also
setName:
(page 54)
Declared in
NSEntityDescription.h
properties
Returns an array containing the properties of the receiver.
- (NSArray *)properties
Return Value An array containing the properties of the receiver. The elements in the array are instances of NSAttributeDescription, NSRelationshipDescription, and/or NSFetchedPropertyDescription. Availability Available in OS X v10.4 and later. See Also (page 50) setProperties: (page 54) attributesByName (page 45) relationshipsByName (page 50)
propertiesByName
49
Declared in
NSEntityDescription.h
propertiesByName
Returns a dictionary containing the properties of the receiver.
- (NSDictionary *)propertiesByName
Return Value A dictionary containing the receivers properties, where the keys in the dictionary are the property names and the values are instances of NSAttributeDescription and/or NSRelationshipDescription. Availability Available in OS X v10.4 and later. See Also (page 45) relationshipsByName (page 50)
attributesByName relationshipsWithDestinationEntity:
(page 51)
Declared in
NSEntityDescription.h
relationshipsByName
Returns the relationships of the receiver in a dictionary, where the keys in the dictionary are the relationship names.
- (NSDictionary *)relationshipsByName
Return Value The relationships of the receiver in a dictionary, where the keys in the dictionary are the relationship names and the values are instances of NSRelationshipDescription. Availability Available in OS X v10.4 and later. See Also (page 45) propertiesByName (page 50)
attributesByName relationshipsWithDestinationEntity:
(page 51)
50
Declared in
NSEntityDescription.h
relationshipsWithDestinationEntity:
Returns an array containing the relationships of the receiver where the entity description of the relationship is a given entity.
- (NSArray *)relationshipsWithDestinationEntity:(NSEntityDescription *)entity
Parameters
entity
An entity description. Return Value An array containing the relationships of the receiver where the entity description of the relationship is entity. Elements in the array are instances of NSRelationshipDescription. Availability Available in OS X v10.4 and later. See Also (page 45) propertiesByName (page 50) relationshipsByName (page 50)
attributesByName
Declared in
NSEntityDescription.h
renamingIdentifier
Returns the renaming identifier for the receiver.
- (NSString *)renamingIdentifier
Return Value The renaming identifier for the receiver. Discussion The renaming identifier is used to resolve naming conflicts between models. When creating a mapping model between two managed object models, a source entity and a destination entity that share the same identifier indicate that an entity mapping should be configured to migrate from the source to the destination.
51
If you do not set this value, the identifier will return the entitys name. Availability Available in OS X v10.6 and later. See Also
setRenamingIdentifier:
(page 55)
Declared in
NSEntityDescription.h
setAbstract:
Sets whether the receiver represents an abstract entity.
- (void)setAbstract:(BOOL)flag
Parameters
flag
A Boolean value indicating whether the receiver is abstract (YES) or not (NO). Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also
isAbstract
(page 47)
Declared in
NSEntityDescription.h
setCompoundIndexes:
Sets the compound indexes for the entity as an array of arrays.
- (void)setCompoundIndexes:(NSArray *)value
52
Parameters
value
An array of arrays. The arrays contained in value must contain instances of NSAttributeDescription, NSRelationshipDescription that represent properties of the entity, or of NSString that match the name of attributes or relationships of the entity. Discussion Compound indexes are only used by stores that natively support compound indices (the setting is thus only advisory). Indexes apply to the entire inheritance hierarchy. Availability Available in OS X v10.8 and later. See Also
compoundIndexes
(page 46)
Declared in
NSEntityDescription.h
setManagedObjectClassName:
Sets the name of the class that represents the receivers entity.
- (void)setManagedObjectClassName:(NSString *)name
Parameters
name
The name of the class that represents the receivers entity. Discussion The class specified by name must either be, or inherit from, NSManagedObject. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also
managedObjectClassName
(page 48)
53
Declared in
NSEntityDescription.h
setName:
Sets the entity name of the receiver.
- (void)setName:(NSString *)name
Parameters
name
The name of the entity the receiver describes. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also name (page 49)
Related Sample Code Core Data Utility
Declared in
NSEntityDescription.h
setProperties:
Sets the properties array of the receiver.
- (void)setProperties:(NSArray *)properties
Parameters
properties
An array of properties (instances of NSAttributeDescription, NSRelationshipDescription, and/or NSFetchedPropertyDescription). Special Considerations This method raises an exception if the receivers model has been used by an object graph manager.
54
Availability Available in OS X v10.4 and later. See Also (page 49) propertiesByName (page 50) attributesByName (page 45) relationshipsByName (page 50)
properties
Declared in
NSEntityDescription.h
setRenamingIdentifier:
Sets the renaming identifier for the receiver.
- (void)setRenamingIdentifier:(NSString *)value
Parameters
value
The renaming identifier for the receiver. Availability Available in OS X v10.6 and later. See Also
renamingIdentifier
(page 51)
Declared in
NSEntityDescription.h
setSubentities:
Sets the subentities of the receiver.
- (void)setSubentities:(NSArray *)array
55
Parameters
array
An array containing sub-entities for the receiver. Objects in the array must be instances of NSEntityDescription. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also (page 57) subentitiesByName (page 58) superentity (page 58)
subentities
Declared in
NSEntityDescription.h
setUserInfo:
Sets the user info dictionary of the receiver.
- (void)setUserInfo:(NSDictionary *)dictionary
Parameters
dictionary
A user info dictionary. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also
userInfo
(page 59)
Declared in
NSEntityDescription.h
56
setVersionHashModifier:
Sets the version hash modifier for the receiver.
- (void)setVersionHashModifier:(NSString *)modifierString
Parameters
modifierString
The version hash modifier for the receiver. Discussion This value is included in the version hash for the entity. You use it to mark or denote an entity as being a different version than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where, for example, the structure of an entity is unchanged but the format or content of data has changed.) Availability Available in OS X v10.5 and later. See Also
versionHash
versionHashModifier
Declared in
NSEntityDescription.h
subentities
Returns an array containing the sub-entities of the receiver.
- (NSArray *)subentities
Return Value An array containing the receivers sub-entities. The sub-entities are instances of NSEntityDescription. Availability Available in OS X v10.4 and later. See Also (page 55) subentitiesByName (page 58) superentity (page 58)
setSubentities:
57
Declared in
NSEntityDescription.h
subentitiesByName
Returns the sub-entities of the receiver in a dictionary.
- (NSDictionary *)subentitiesByName
Return Value A dictionary containing the receivers sub-entities. The keys in the dictionary are the sub-entity names, the corresponding values are instances of NSEntityDescription. Availability Available in OS X v10.4 and later. See Also (page 55) subentities (page 57) superentity (page 58)
setSubentities:
Declared in
NSEntityDescription.h
superentity
Returns the super-entity of the receiver.
- (NSEntityDescription *)superentity
Return Value The receivers super-entity. If the receiver has no super-entity, returns nil. Availability Available in OS X v10.4 and later. See Also (page 55) subentities (page 57) subentitiesByName (page 58)
setSubentities:
58
Declared in
NSEntityDescription.h
userInfo
Returns the user info dictionary of the receiver.
- (NSDictionary *)userInfo
Return Value The receivers user info dictionary. Availability Available in OS X v10.4 and later. See Also
setUserInfo:
(page 56)
Declared in
NSEntityDescription.h
versionHash
Returns the version hash for the receiver.
- (NSData *)versionHash
Return Value The version hash for the receiver. Discussion The version hash is used to uniquely identify an entity based on the collection and configuration of properties for the entity. The version hash uses only values which affect the persistence of data and the user-defined versionHashModifier (page 60) value. (The values which affect persistence are: the name of the entity, the version hash of the superentity (if present), if the entity is abstract, and all of the version hashes for the properties.) This value is stored as part of the version information in the metadata for stores which use this entity, as well as a definition of an entity involved in an NSEntityMapping object. Availability Available in OS X v10.5 and later. See Also
versionHashModifier
(page 60)
59
setVersionHashModifier:
(page 57)
Declared in
NSEntityDescription.h
versionHashModifier
Returns the version hash modifier for the receiver.
- (NSString *)versionHashModifier
Return Value The version hash modifier for the receiver. Discussion This value is included in the version hash for the entity. See setVersionHashModifier: (page 57) for a full discussion. Availability Available in OS X v10.5 and later. See Also
versionHash
setVersionHashModifier:
Declared in
NSEntityDescription.h
60
NSObject NSObject (NSObject) /System/Library/Frameworks/CoreData.framework Available in OS X v10.5 and later. CoreData/NSEntityMapping.h Core Data Model Versioning and Data Migration Programming Guide
Overview
Instances of NSEntityMapping specify how to map an entity from a source to a destination managed object model.
Tasks
Managing Source Information
sourceEntityName
(page 72) Returns the source entity name for the receiver. (page 70) Sets the source entity name for the receiver. (page 72) Returns the version hash for the source entity for the receiver. (page 70) Sets the version hash for the source entity for the receiver. (page 73) Returns the source expression for the receiver.
setSourceEntityName:
sourceEntityVersionHash
setSourceEntityVersionHash:
sourceExpression
61
setSourceExpression:
(page 63) Returns the destination entity name for the receiver. (page 67) Sets the destination entity name for the receiver. (page 64) Returns the version hash for the destination entity for the receiver. (page 67) Sets the version hash for the destination entity for the receiver.
setDestinationEntityName:
destinationEntityVersionHash
setDestinationEntityVersionHash:
(page 65) Returns the name of the receiver. (page 69) Sets the name of the receiver. (page 65) Returns the mapping type for the receiver. (page 68) Sets the mapping type for the receiver. (page 65) Returns the class name of the migration policy for the receiver. (page 68) Sets the class name of the migration policy for the receiver. (page 63) Returns the array of attribute mappings for the receiver. (page 67) Sets the array of attribute mappings for the receiver.
setName:
mappingType
setMappingType:
entityMigrationPolicyClassName
setEntityMigrationPolicyClassName:
attributeMappings
setAttributeMappings:
62
relationshipMappings
(page 66) Returns the array of relationship mappings for the receiver. (page 69) Sets the array of relationship mappings for the receiver. (page 73) Returns the user info dictionary for the receiver. (page 71) Sets the user info dictionary for the receiver.
setRelationshipMappings:
userInfo
setUserInfo:
Instance Methods
attributeMappings
Returns the array of attribute mappings for the receiver.
- (NSArray *)attributeMappings
Return Value The array of attribute mappings for the receiver. Special Considerations The order of mappings in the array specifies the order in which the mappings will be processed during a migration. Availability Available in OS X v10.5 and later. See Also (page 67) relationshipMappings (page 66)
setAttributeMappings:
Declared in
NSEntityMapping.h
destinationEntityName
Returns the destination entity name for the receiver.
- (NSString *)destinationEntityName
63
Return Value The destination entity name for the receiver. Discussion Mappings are not directly bound to entity descriptions. You can use the migration managers destinationEntityForEntityMapping: method to retrieve the entity description for this entity name. Availability Available in OS X v10.5 and later. See Also
setDestinationEntityName: sourceEntityName
(page 67)
(page 72)
Declared in
NSEntityMapping.h
destinationEntityVersionHash
Returns the version hash for the destination entity for the receiver.
- (NSData *)destinationEntityVersionHash
Return Value The version hash for the destination entity for the receiver. Discussion The version hash is calculated by Core Data based on the property values of the entity (see NSEntityDescriptions versionHash (page 59) method). The destinationEntityVersionHash must equal the version hash of the destination entity represented by the mapping. Availability Available in OS X v10.5 and later. See Also
setDestinationEntityVersionHash: sourceEntityVersionHash
(page 67)
(page 72)
Declared in
NSEntityMapping.h
64
entityMigrationPolicyClassName
Returns the class name of the migration policy for the receiver.
- (NSString *)entityMigrationPolicyClassName
Return Value The class name of the migration policy for the receiver. Discussion If not specified, the default migration class name is NSEntityMigrationPolicy. You can specify a subclass to provide custom behavior. Availability Available in OS X v10.5 and later. See Also
setEntityMigrationPolicyClassName:
(page 68)
Declared in
NSEntityMapping.h
mappingType
Returns the mapping type for the receiver.
- (NSEntityMappingType)mappingType
Return Value The mapping type for the receiver. Availability Available in OS X v10.5 and later. See Also
setMappingType:
(page 68)
Declared in
NSEntityMapping.h
name
Returns the name of the receiver.
65
- (NSString *)name
Return Value The name of the receiver. Discussion The name is used only as a means of distinguishing mappings in a model. If not specified, the value defaults to SOURCE ->DESTINATION . Availability Available in OS X v10.5 and later. See Also
setName:
(page 69)
Declared in
NSEntityMapping.h
relationshipMappings
Returns the array of relationship mappings for the receiver.
- (NSArray *)relationshipMappings
Return Value The array of relationship mappings for the receiver. Special Considerations The order of mappings in the array specifies the order in which the mappings will be processed during a migration. Availability Available in OS X v10.5 and later. See Also (page 69) attributeMappings (page 63)
setRelationshipMappings:
Declared in
NSEntityMapping.h
66
setAttributeMappings:
Sets the array of attribute mappings for the receiver.
- (void)setAttributeMappings:(NSArray *)mappings
Parameters
mappings
The array of attribute mappings for the receiver. Availability Available in OS X v10.5 and later. See Also (page 63) setRelationshipMappings: (page 69)
attributeMappings
Declared in
NSEntityMapping.h
setDestinationEntityName:
Sets the destination entity name for the receiver.
- (void)setDestinationEntityName:(NSString *)name
Parameters
name
The destination entity name. Availability Available in OS X v10.5 and later. See Also (page 63) setSourceEntityName: (page 70)
destinationEntityName
Declared in
NSEntityMapping.h
setDestinationEntityVersionHash:
Sets the version hash for the destination entity for the receiver.
67
- (void)setDestinationEntityVersionHash:(NSData *)vhash
Parameters
vhash
The version hash for the destination entity. Availability Available in OS X v10.5 and later. See Also (page 64) setSourceEntityVersionHash: (page 70)
destinationEntityVersionHash
Declared in
NSEntityMapping.h
setEntityMigrationPolicyClassName:
Sets the class name of the migration policy for the receiver.
- (void)setEntityMigrationPolicyClassName:(NSString *)name
Parameters
name
The class name of the migration policy (either NSEntityMigrationPolicy or a subclass of NSEntityMigrationPolicy). Availability Available in OS X v10.5 and later. See Also
entityMigrationPolicyClassName
(page 65)
Declared in
NSEntityMapping.h
setMappingType:
Sets the mapping type for the receiver.
- (void)setMappingType:(NSEntityMappingType)type
68
Parameters
type
The mapping type for the receiver. Discussion If you specify a custom entity mapping type, you must specify a value for the migration policy class name as well (see setEntityMigrationPolicyClassName: (page 68)). Availability Available in OS X v10.5 and later. See Also
mappingType
(page 65)
Declared in
NSEntityMapping.h
setName:
Sets the name of the receiver.
- (void)setName:(NSString *)name
Parameters
name
The name of the receiver. Availability Available in OS X v10.5 and later. See Also name (page 65) Declared in
NSEntityMapping.h
setRelationshipMappings:
Sets the array of relationship mappings for the receiver.
- (void)setRelationshipMappings:(NSArray *)mappings
69
Parameters
mappings
The array of relationship mappings for the receiver. Availability Available in OS X v10.5 and later. See Also (page 66) setAttributeMappings: (page 67)
relationshipMappings
Declared in
NSEntityMapping.h
setSourceEntityName:
Sets the source entity name for the receiver.
- (void)setSourceEntityName:(NSString *)name
Parameters
name
The source entity name for the receiver. Availability Available in OS X v10.5 and later. See Also
sourceEntityName
setDestinationEntityName:
Declared in
NSEntityMapping.h
setSourceEntityVersionHash:
Sets the version hash for the source entity for the receiver.
- (void)setSourceEntityVersionHash:(NSData *)vhash
70
Parameters
vhash
The version hash for the source entity for the receiver. Availability Available in OS X v10.5 and later. See Also
sourceEntityVersionHash
setDestinationEntityVersionHash:
Declared in
NSEntityMapping.h
setSourceExpression:
Sets the source expression for the receiver.
- (void)setSourceExpression:(NSExpression *)source
Parameters
source
The source expression for the receiver. The expression can be a fetch request expression, or any other expression which evaluates to a collection. Availability Available in OS X v10.5 and later. See Also
sourceExpression
(page 73)
Declared in
NSEntityMapping.h
setUserInfo:
Sets the user info dictionary for the receiver.
- (void)setUserInfo:(NSDictionary *)dict
Parameters
dict
71
Discussion You can set the contents of the dictionary using the appropriate inspector in the Xcode mapping model editor. Availability Available in OS X v10.5 and later. See Also
userInfo
(page 73)
Declared in
NSEntityMapping.h
sourceEntityName
Returns the source entity name for the receiver.
- (NSString *)sourceEntityName
Return Value The source entity name for the receiver. Discussion Mappings are not directly bound to entity descriptions; you can use the sourceEntityForEntityMapping: method on the migration manager to retrieve the entity description for this entity name. Availability Available in OS X v10.5 and later. See Also (page 70) destinationEntityName (page 63)
setSourceEntityName:
Declared in
NSEntityMapping.h
sourceEntityVersionHash
Returns the version hash for the source entity for the receiver.
- (NSData *)sourceEntityVersionHash
72
Return Value The version hash for the source entity for the receiver. Discussion The version hash is calculated by Core Data based on the property values of the entity (see NSEntityDescriptions versionHash (page 59) method). The sourceEntityVersionHash must equal the version hash of the source entity represented by the mapping. Availability Available in OS X v10.5 and later. See Also (page 70) destinationEntityVersionHash (page 64)
setSourceEntityVersionHash:
Declared in
NSEntityMapping.h
sourceExpression
Returns the source expression for the receiver.
- (NSExpression *)sourceExpression
Return Value The source expression. The expression can be a fetch request expression, or any other expression which evaluates to a collection. Discussion The source expression is used to obtain the collection of managed objects to process through the mapping. Availability Available in OS X v10.5 and later. See Also
setSourceExpression:
(page 71)
Declared in
NSEntityMapping.h
userInfo
Returns the user info dictionary for the receiver.
73
- (NSDictionary *)userInfo
Return Value The user info dictionary. Discussion You can use the info dictionary in any way that might be useful in your migration. You set the contents of the dictionary using setUserInfo: (page 71) or using the appropriate inspector in the Xcode mapping model editor. Availability Available in OS X v10.5 and later. See Also
setUserInfo:
(page 71)
Declared in
NSEntityMapping.h
Constants
Entity Mapping Types
These constants specify the types of entity mapping.
= = = = = =
Constants
NSUndefinedEntityMappingType
Specifies that the developer handles destination instance creation. Available in OS X v10.5 and later. Declared in NSEntityMapping.h.
74
NSCustomEntityMappingType
Specifies that this is a new entity in the destination model. Instances of the entity only exist in the destination. Available in OS X v10.5 and later. Declared in NSEntityMapping.h.
NSRemoveEntityMappingType
Specifies that this entity is not present in the destination model. Instances of the entity only exist in the sourcesource instances are not mapped to destination. Available in OS X v10.5 and later. Declared in NSEntityMapping.h.
NSCopyEntityMappingType
Specifies that source instances are migrated as-is. Available in OS X v10.5 and later. Declared in NSEntityMapping.h.
NSTransformEntityMappingType
Specifies that entity exists in source and destination and is mapped. Available in OS X v10.5 and later. Declared in NSEntityMapping.h. Declared in
NSEntityMapping.h
NSEntityMappingType
Data type used for constants that specify types of entity mapping.
Discussion For possible values, see Entity Mapping Types (page 74). Availability Available in OS X v10.5 and later.
75
Declared in
NSEntityMapping.h
76
NSObject NSObject (NSObject) /System/Library/Frameworks/CoreData.framework Available in OS X v10.5 and later. CoreData/NSEntityMigrationPolicy.h Core Data Model Versioning and Data Migration Programming Guide
Overview
Instances of NSEntityMigrationPolicy customize the migration process for an entity mapping. You set the policy for an entity mapping by passing the name of the migration policy class as the argument to setEntityMigrationPolicyClassName: (page 68) (typically you specify the name in the Xcode mapping model editor).
Tasks
Customizing Stages of the Mapping Life Cycle
beginEntityMapping:manager:error:
(page 78) Invoked by the migration manager at the start of a given entity mapping. (page 79) Creates the destination instance(s) for a given source instance.
createDestinationInstancesForSourceInstance:entityMapping:manager:error:
endInstanceCreationForEntityMapping:manager:error:
(page 81) Indicates the end of the creation stage for the specified entity mapping, and the precursor to the next migration stage.
77
createRelationshipsForDestinationInstance:entityMapping:manager:error:
(page 80)
(page 82) Indicates the end of the relationship creation stage for the specified entity mapping. (page 83) Invoked during the validation stage of the entity migration policy, providing the option of performing custom validation on migrated objects. (page 81) Invoked by the migration manager at the end of a given entity mapping.
performCustomValidationForEntityMapping:manager:error:
endEntityMapping:manager:error:
Instance Methods
beginEntityMapping:manager:error:
Invoked by the migration manager at the start of a given entity mapping.
- (BOOL)beginEntityMapping:(NSEntityMapping *)mapping
Parameters
mapping
If an error occurs, upon return contains an NSError object that describes the problem. Return Value YES if the method completes successfully, otherwise NO. Discussion This method is the precursor to the creation stage. In a custom class, you can implement this method to set up any state information that will be useful for the duration of the migration. Availability Available in OS X v10.5 and later.
78
See Also
createDestinationInstancesForSourceInstance:entityMapping:manager:error: endEntityMapping:manager:error:
(page 79)
(page 81)
Declared in
NSEntityMigrationPolicy.h
createDestinationInstancesForSourceInstance:entityMapping:manager:error:
Creates the destination instance(s) for a given source instance.
- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance
Parameters
sInstance
If an error occurs, upon return contains an NSError object that describes the problem. Return Value YES if the method completes successfully, otherwise NO. Discussion This method is invoked by the migration manager on each source instance (as specified by the sourceExpression (page 73) in the mapping) to create the corresponding destination instance(s). It also associates the source and destination instances by calling NSMigrationManagers associateSourceInstance:withDestinationInstance:forEntityMapping: method. Special Considerations If you override this method and do not invoke super, you must invoke NSMigrationManagers associateSourceInstance:withDestinationInstance:forEntityMapping: to associate the source and destination instances as required. .
79
endInstanceCreationForEntityMapping:manager:error:
Declared in
NSEntityMigrationPolicy.h
createRelationshipsForDestinationInstance:entityMapping:manager:error:
Constructs the relationships between the newly-created destination instances.
- (BOOL)createRelationshipsForDestinationInstance:(NSManagedObject *)dInstance
Parameters
dInstance
If an error occurs, upon return contains an NSError object that describes the problem. Return Value YES if the relationships are constructed correctly, otherwise NO. Discussion You can use this stage to (re)create relationships between migrated objectsyou use the association lookup methods on the NSMigrationManager instance to determine the appropriate relationship targets. Availability Available in OS X v10.5 and later. See Also (page 81) endRelationshipCreationForEntityMapping:manager:error: (page 82)
endInstanceCreationForEntityMapping:manager:error:
80
Declared in
NSEntityMigrationPolicy.h
endEntityMapping:manager:error:
Invoked by the migration manager at the end of a given entity mapping.
- (BOOL)endEntityMapping:(NSEntityMapping *)mapping
Parameters
mapping
If an error occurs, upon return contains an NSError object that describes the problem. Return Value YES if the method completes correctly, otherwise NO. Discussion This is the end to the given entity mapping. You can implement this method to perform any clean-up at the end of the migration (from any of the three phases of the mapping). Availability Available in OS X v10.5 and later. See Also
performCustomValidationForEntityMapping:manager:error: beginEntityMapping:manager:error:
(page 83)
(page 78)
Declared in
NSEntityMigrationPolicy.h
endInstanceCreationForEntityMapping:manager:error:
Indicates the end of the creation stage for the specified entity mapping, and the precursor to the next migration stage.
81
- (BOOL)endInstanceCreationForEntityMapping:(NSEntityMapping *)mapping
Parameters
mapping
If an error occurs, upon return contains an NSError object that describes the problem. Return Value YES if the relationships are constructed correctly, otherwise NO. Discussion You can override this method to clean up state from the creation of destination or to prepare state for the creation of relationships. Availability Available in OS X v10.5 and later. See Also (page 79) createRelationshipsForDestinationInstance:entityMapping:manager:error: (page 80)
createDestinationInstancesForSourceInstance:entityMapping:manager:error:
Declared in
NSEntityMigrationPolicy.h
endRelationshipCreationForEntityMapping:manager:error:
Indicates the end of the relationship creation stage for the specified entity mapping.
- (BOOL)endRelationshipCreationForEntityMapping:(NSEntityMapping *)mapping
Parameters
mapping
82
manager
If an error occurs, upon return contains an NSError object that describes the problem. Return Value YES if the method completes correctly, otherwise NO. Discussion This method is invoked after
createRelationshipsForDestinationInstance:entityMapping:manager:error: (page 80); you can override
it to clean up state from the creation of relationships, or prepare state for custom validation in performCustomValidationForEntityMapping:manager:error: (page 83). Availability Available in OS X v10.5 and later. See Also
createRelationshipsForDestinationInstance:entityMapping:manager:error: performCustomValidationForEntityMapping:manager:error:
(page 80)
(page 83)
Declared in
NSEntityMigrationPolicy.h
performCustomValidationForEntityMapping:manager:error:
Invoked during the validation stage of the entity migration policy, providing the option of performing custom validation on migrated objects.
- (BOOL)performCustomValidationForEntityMapping:(NSEntityMapping *)mapping
Parameters
mapping
If an error occurs, upon return contains an NSError object that describes the problem.
83
Return Value YES if the method completes correctly, otherwise NO. Discussion This method is called before the default save validation is performed by the framework. If you implement this method, you must manually obtain the collection of objects you are interested in validating. Availability Available in OS X v10.5 and later. See Also
endRelationshipCreationForEntityMapping:manager:error: endEntityMapping:manager:error:
(page 82)
(page 81)
Declared in
NSEntityMigrationPolicy.h
Constants
Value Expression Keys
Keys used in value expression right hand sides.
Constants
NSMigrationManagerKey
Key for the migration manager. To access this key in a custom value expression string in the Xcode mapping model editor use $manager. Available in OS X v10.5 and later. Declared in NSEntityMigrationPolicy.h.
84
NSMigrationSourceObjectKey
Key for the source object. To access this key in a custom value expression string in the Xcode mapping model editor use $source. Available in OS X v10.5 and later. Declared in NSEntityMigrationPolicy.h.
NSMigrationDestinationObjectKey
Key for the destination object. To access this key in a custom value expression string in the Xcode mapping model editor use $destination. Available in OS X v10.5 and later. Declared in NSEntityMigrationPolicy.h.
NSMigrationEntityMappingKey
Key for the entity mapping object. To access this key in a custom value expression string in the Xcode mapping model editor use $entityMapping. Available in OS X v10.5 and later. Declared in NSEntityMigrationPolicy.h.
NSMigrationPropertyMappingKey
Key for the property mapping object. To access this key in a custom value expression string in the Xcode mapping model editor use $propertyMapping. Available in OS X v10.5 and later. Declared in NSEntityMigrationPolicy.h.
NSMigrationEntityPolicyKey
Key for the entity migration policy object. To access this key in a custom value expression string in the Xcode mapping model editor use $entityPolicy. Available in OS X v10.6 and later. Declared in NSEntityMigrationPolicy.h. Discussion You can use these keys in the right hand sides of a value expression.
85
NSExpressionDescription
/System/Library/Frameworks/CoreData.framework Available in OS X v10.6 and later. CoreData/NSExpressionDescription.h Core Data Model Versioning and Data Migration Programming Guide
Overview
Instances of NSExpressionDescription objects represent a special property description type intended for use with the NSFetchRequest propertiesToFetch (page 106) method. An NSExpressionDescription describes a column to be returned from a fetch that may not appear directly as an attribute or relationship on an entity. Examples might include upper(attribute) or max(attribute). You cannot set an NSExpressionDescription object as a property of an entity.
Tasks
Getting Information About an Expression Description
expression
(page 87) Returns the expression for the receiver. (page 88) Sets the expression for the receiver.
setExpression:
86
expressionResultType
(page 87) Returns the type of the receiver. (page 88) Sets the type of the receiver.
setExpressionResultType:
Instance Methods
expression
Returns the expression for the receiver.
- (NSExpression *)expression
Return Value The expression for the receiver. Availability Available in OS X v10.6 and later. See Also
setExpression:
(page 88)
Declared in
NSExpressionDescription.h
expressionResultType
Returns the type of the receiver.
- (NSAttributeType)expressionResultType
Return Value The type of the receiver. Availability Available in OS X v10.6 and later. See Also
expressionResultType
(page 87)
87
Declared in
NSExpressionDescription.h
setExpression:
Sets the expression for the receiver.
- (void)setExpression:(NSExpression *)expression
Parameters
expression
The expression for the receiver. Special Considerations This method raises an exception if the receiver model s has been used by an object graph manager. Availability Available in OS X v10.6 and later. See Also
expression
(page 87)
Declared in
NSExpressionDescription.h
setExpressionResultType:
Sets the type of the receiver.
- (void)setExpressionResultType:(NSAttributeType)type
Parameters
type
An NSAttributeType constant that specifies the type for the receiver. Special Considerations This method raises an exception if the receiver model s has been used by an object graph manager. Availability Available in OS X v10.6 and later. See Also
setExpressionResultType:
(page 88)
88
Declared in
NSExpressionDescription.h
89
/System/Library/Frameworks/CoreData.framework Available in OS X v10.4 and later. CoreData/NSFetchedPropertyDescription.h Core Data Programming Guide Predicate Programming Guide
Overview
The NSFetchedPropertyDescription class is used to define fetched properties. Fetched properties allow you to specify related objects through a weak, unidirectional relationship defined by a fetch request. An example might be a iTunes playlist, if expressed as a property of a containing object. Songs dont belong to a particular playlist, especially in the case that theyre on a remote server. The playlist may remain even after the songs have been deleted, or the remote server has become inaccessible. Note, however, that unlike a playlist a fetched property is staticit does not dynamically update itself as objects in the destination entity change. The effect of a fetched property is similar to executing a fetch request yourself and placing the results in a transient attribute, although with the framework managing the details. In particular, a fetched property is not fetched until it is requested, and the results are then cached until the object is turned into a fault. You use refreshObject:mergeChanges: (page 203) (NSManagedObjectContext) to manually refresh the propertiesthis causes the fetch request associated with this property to be executed again when the object fault is next fired.
90
Unlike other relationships, which are all sets, fetched properties are represented by an ordered NSArray object just as if you executed the fetch request yourself. The fetch request associated with the property can have a sort ordering. The value for a fetched property of a managed object does not support mutableArrayValueForKey:.
Tasks
Getting and Setting the Fetch Request
fetchRequest
(page 91) Returns the fetch request of the receiver. (page 92) Sets the fetch request of the receiver.
setFetchRequest:
Instance Methods
fetchRequest
Returns the fetch request of the receiver.
- (NSFetchRequest *)fetchRequest
91
Return Value The fetch request of the receiver. Availability Available in OS X v10.4 and later. See Also
setFetchRequest:
(page 92)
Declared in
NSFetchedPropertyDescription.h
setFetchRequest:
Sets the fetch request of the receiver.
- (void)setFetchRequest:(NSFetchRequest *)fetchRequest
Parameters
fetchRequest
The fetch request of the receiver. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also
fetchRequest
(page 91)
Declared in
NSFetchedPropertyDescription.h
92
/System/Library/Frameworks/CoreData.framework Available in OS X v10.4 and later. CoreData/NSFetchRequest.h Core Data Programming Guide Predicate Programming Guide
Overview
An instance of NSFetchRequest describes search criteria used to retrieve data from a persistent store. An instance collects the criteria needed to select andoptionallyorder a group of managed objects, or data about records held in a persistent store. A fetch request must contain an entity description (an instance of NSEntityDescription) that specifies which entity to search. It frequently also contains:
A predicate (an instance of NSPredicate) that specifies which properties to select by and the constraints on selection, for example last name begins with a J If you . dont specify a predicate, then all instances of the specified entity are selected (subject to other constraints, see executeFetchRequest:error: (page 192) for full details). An array of sort descriptors (instances of NSSortDescriptor) that specify how the returned objects should be ordered, for example by last name then by first name.
93
You can also specify other aspects of a fetch requestthe maximum number of objects that a request should return, and which data stores the request should access. With OS X v10.5 and later you can also specify, for example, whether the fetch returns managed objects or just object IDs, and whether objects are fully populated with their properties (see resultType (page 108), includesSubentities (page 104), includesPropertyValues (page 103), and returnsObjectsAsFaults (page 109)). With OS X v10.6 and later and on iOS, you can further specify, for example, what properties to fetch, the fetch offset, and whether, when the fetch is executed it matches against currently unsaved changes in the managed object context (see resultType (page 108), propertiesToFetch (page 106), fetchOffset (page 101), and includesPendingChanges (page 102)). You can also fetch distinct property values, and attribute values that satisfy a given function, as illustrated in Core Data Snippets . You use NSFetchRequest objects with the method executeFetchRequest:error: (page 192), defined by NSManagedObjectContext. You often predefine fetch requests in a managed object modelNSManagedObjectModel provides API to retrieve a stored fetch request by name. Stored fetch requests can include placeholders for variable substitution, and so serve as templates for later completion. Fetch request templates therefore allow you to pre-define queries with variables that are substituted at runtime.
Tasks
Managing the Fetch Requests Entity
+ fetchRequestWithEntityName:
(page 97) Returns a fetch request configured with a given entity name. (page 104) Initializes a fetch request configured with a given entity name (page 99) Returns the name of the entity the request is configured to fetch. (page 99) Returns the entity specified for the receiver. (page 110) Sets the entity of the receiver. (page 104) Returns a Boolean value that indicates whether the receiver includes subentities in the results.
initWithEntityName:
entityName
entity
setEntity:
includesSubentities
94
setIncludesSubentities:
Fetch Constraints
predicate
(page 105) Returns the predicate of the receiver. (page 115) Sets the predicate of the receiver. (page 100) Returns the fetch limit of the receiver. (page 111) Sets the fetch limit of the receiver. (page 101) Returns the fetch offset of the receiver. (page 112) Sets the fetch offset of the receiver. (page 100) Returns the batch size of the receiver. (page 111) Sets the batch size for the receiver. (page 98) Returns an array containing the persistent stores specified for the receiver. (page 110) Sets the array of persistent stores that will be searched by the receiver.
setPredicate:
fetchLimit
setFetchLimit:
fetchOffset
setFetchOffset:
fetchBatchSize
setFetchBatchSize:
affectedStores
setAffectedStores:
Sorting
sortDescriptors
(page 120) Returns the sort descriptors of the receiver. (page 119) Sets the array of sort descriptors of the receiver.
setSortDescriptors:
95
Prefetching
relationshipKeyPathsForPrefetching
(page 107) Returns the array of relationship key paths to prefetch along with the entity for the request. (page 117) Sets an array of relationship key paths to prefetch along with the entity for the request.
setRelationshipKeyPathsForPrefetching:
(page 108) Returns the result type of the receiver. (page 117) Sets the result type of the receiver. (page 102) Returns a Boolean value that indicates whether, when the fetch is executed it matches against currently unsaved changes in the managed object context. (page 113) Sets if, when the fetch is executed, it matches against currently unsaved changes in the managed object context. (page 106) Returns an array of NSPropertyDescription objects that specify which properties should be returned by the fetch. (page 115) Specifies which properties should be returned by the fetch. (page 108) Returns a Boolean value that indicates whether the fetch request returns only distinct values for the fields specified by propertiesToFetch. (page 118) Sets whether the request should return only distinct values for the fields specified by propertiesToFetch. (page 103) Returns a Boolean value that indicates whether, when the fetch is executed, property data is obtained from the persistent store. (page 114) Sets if, when the fetch is executed, property data is obtained from the persistent store.
setResultType:
includesPendingChanges
setIncludesPendingChanges:
propertiesToFetch
setPropertiesToFetch:
returnsDistinctResults
setReturnsDistinctResults:
includesPropertyValues
setIncludesPropertyValues:
96
shouldRefreshRefetchedObjects
(page 120) Returns a Boolean value that indicates whether the property values of fetched objects will be updated with the current values in the persistent store. (page 119) Sets whether the fetch request should cause property values of fetched objects to be updated with the current values in the persistent store. (page 109) Returns a Boolean value that indicates whether the objects resulting from a fetch using the receiver are faults. (page 118) Sets whether the objects resulting from a fetch request are faults.
setShouldRefreshRefetchedObjects:
returnsObjectsAsFaults
setReturnsObjectsAsFaults:
(page 106) Returns an array of objects that indicate how data should be grouped before a select statement is run in an SQL database. (page 116) Sets array of objects that indicate how data should be grouped before a select statement is run in an SQL database. (page 102) Returns the predicate used to filter rows being returned by a query containing a GROUP BY. (page 112) Sets the predicate to use to filter rows being returned by a query containing a GROUP BY.
setPropertiesToGroupBy:
havingPredicate
setHavingPredicate:
Class Methods
fetchRequestWithEntityName:
Returns a fetch request configured with a given entity name.
+ (NSFetchRequest *)fetchRequestWithEntityName:(NSString *)entityName
Parameters
entityName
97
Return Value A fetch request configured to fetch using the entity named entityName. Discussion This method provides a convenient way to configure the entity for a fetch request without having to retrieve an NSEntityDescription object. When the fetch is executed, the request uses the managed object context to find the entity with the given name. The model associated with the contexts persistent store coordinator must contain an entity named entityName. Availability Available in OS X v10.7 and later. See Also
initWithEntityName:
(page 104)
Declared in
NSFetchRequest.h
Instance Methods
affectedStores
Returns an array containing the persistent stores specified for the receiver.
- (NSArray *)affectedStores
Return Value An array containing the persistent stores specified for the receiver. Availability Available in OS X v10.4 and later. See Also
setAffectedStores:
(page 110)
Declared in
NSFetchRequest.h
98
entity
Returns the entity specified for the receiver.
- (NSEntityDescription *)entity
Return Value The entity specified for the receiver. Availability Available in OS X v10.4 and later. See Also
setEntity:
(page 110)
Declared in
NSFetchRequest.h
entityName
Returns the name of the entity the request is configured to fetch.
- (NSString *)entityName
Return Value The name of the entity the request is configured to fetch. Availability Available in OS X v10.7 and later. See Also
+ fetchRequestWithEntityName: initWithEntityName:
Declared in
NSFetchRequest.h
99
fetchBatchSize
Returns the batch size of the receiver.
- (NSUInteger)fetchBatchSize
Return Value The batch size of the receiver. Discussion The default value is 0. A batch size of 0 is treated as infinite, which disables the batch faulting behavior. If you set a non-zero batch size, the collection of objects returned when the fetch is executed is broken into batches. When the fetch is executed, the entire request is evaluated and the identities of all matching objects recorded, but no more than batchSize objects data will be fetched from the persistent store at a time. The array returned from executing the request will be a proxy object that transparently faults batches on demand. (In database terms, this is an in-memory cursor.) You can use this feature to restrict the working set of data in your application. In combination with fetchLimit (page 100), you can create a subrange of an arbitrary result set. Special Considerations For purposes of thread safety, you should consider the array proxy returned when the fetch is executed as being owned by the managed object context the request is executed against, and treat it as if it were a managed object registered with that context. Availability Available in OS X v10.6 and later. See Also (page 111) fetchLimit (page 100)
setFetchBatchSize:
Declared in
NSFetchRequest.h
fetchLimit
Returns the fetch limit of the receiver.
- (NSUInteger)fetchLimit
100
Return Value The fetch limit of the receiver. Discussion The fetch limit specifies the maximum number of objects that a request should return when executed. Special Considerations If you set a fetch limit, the framework makes a best effort, but does not guarantee, to improve efficiency. For every object store except the SQL store, a fetch request executed with a fetch limit in effect simply performs an unlimited fetch and throws away the unasked for rows. Availability Available in OS X v10.4 and later. See Also (page 111) fetchOffset (page 101)
setFetchLimit:
Declared in
NSFetchRequest.h
fetchOffset
Returns the fetch offset of the receiver.
- (NSUInteger)fetchOffset
Return Value The fetch offset of the receiver. Discussion The default value is 0. This setting allows you to specify an offset at which rows will begin being returned. Effectively, the request will skip over the specified number of matching entries. For example, given a fetch which would normally return a, b, c, d, specifying an offset of 1 will return b, c, d, and an offset of 4 will return an empty array. Offsets are ignored in nested requests such as subqueries. This can be used to restrict the working set of data. In combination with -fetchLimit, you can create a subrange of an arbitrary result set. Availability Available in OS X v10.6 and later.
101
See Also
setFetchOffset: fetchLimit
Declared in
NSFetchRequest.h
havingPredicate
Returns the predicate used to filter rows being returned by a query containing a GROUP BY.
- (NSPredicate *)havingPredicate
Return Value The predicate used to filter rows being returned by a query containing a GROUP BY. Discussion For a full discussion, see setHavingPredicate: (page 112). For a discussion of GROUP BY, see setPropertiesToGroupBy: (page 116). Availability Available in OS X v10.7 and later. See Also (page 112) setPropertiesToGroupBy: (page 116)
setHavingPredicate:
Declared in
NSFetchRequest.h
includesPendingChanges
Returns a Boolean value that indicates whether, when the fetch is executed it matches against currently unsaved changes in the managed object context.
- (BOOL)includesPendingChanges
Return Value YES if, when the fetch is executed it will match against currently unsaved changes in the managed object context, otherwise NO.
102
Discussion For a full discussion, see includesPendingChanges (page 102). Availability Available in OS X v10.6 and later. See Also
setIncludesPendingChanges:
(page 113)
Declared in
NSFetchRequest.h
includesPropertyValues
Returns a Boolean value that indicates whether, when the fetch is executed, property data is obtained from the persistent store.
- (BOOL)includesPropertyValues
Return Value YES if, when the fetch is executed, property data is obtained from the persistent store, otherwise NO. Discussion The default value is YES. You can set includesPropertyValues to NO to reduce memory overhead by avoiding creation of objects to represent the property values. You should typically only do so, however, if you are sure that either you will not need the actual property data or you already have the information in the row cache, otherwise you will incur multiple trips to the database. During a normal fetch (includesPropertyValues is YES), Core Data fetches the object ID and property data for the matching records, fills the row cache with the information, and returns managed object as faults (see returnsObjectsAsFaults (page 109)). These faults are managed objects, but all of their property data still resides in the row cache until the fault is fired. When the fault is fired, Core Data retrieves the data from the row cachethere is no need to go back to the database. If includesPropertyValues is NO, then Core Data fetches only the object ID information for the matching recordsit does not populate the row cache. Core Data still returns managed objects since it only needs managed object IDs to create faults. However, if you subsequently fire the fault, Core Data looks in the (empty) row cache, doesn't find any data, and then goes back to the store a second time for the data. Availability Available in OS X v10.5 and later.
103
See Also
setIncludesPropertyValues:
(page 114)
Declared in
NSFetchRequest.h
includesSubentities
Returns a Boolean value that indicates whether the receiver includes subentities in the results.
- (BOOL)includesSubentities
Return Value YES if the request will include all subentities of the entity for the request, otherwise NO. Discussion The default is YES. Availability Available in OS X v10.5 and later. See Also
setIncludesSubentities:
(page 114)
Declared in
NSFetchRequest.h
initWithEntityName:
Initializes a fetch request configured with a given entity name
- (id)initWithEntityName:(NSString *)entityName
Parameters
entityName
The name of the entity to fetch. Return Value A fetch request configured to fetch using the entity named entityName.
104
Discussion This method provides a convenient way to configure the entity for a fetch request without having to retrieve an NSEntityDescription object. When the fetch is executed, the request uses the managed object context to find the entity with the given name. The model associated with the contexts persistent store coordinator must contain an entity named entityName. Availability Available in OS X v10.7 and later. See Also
+ fetchRequestWithEntityName:
(page 97)
Declared in
NSFetchRequest.h
predicate
Returns the predicate of the receiver.
- (NSPredicate *)predicate
Return Value The predicate of the receiver. Discussion The predicate is used to constrain the selection of objects the receiver is to fetch. For more about predicates, see Predicate Programming Guide . If the predicate is emptyfor example, if it is an AND predicate whose array of elements contains no predicatesthe receiver has its predicate set to nil. For more about predicates, see Predicate Programming Guide . Availability Available in OS X v10.4 and later. See Also
setPredicate:
(page 115)
Declared in
NSFetchRequest.h
105
propertiesToFetch
Returns an array of NSPropertyDescription objects that specify which properties should be returned by the fetch.
- (NSArray *)propertiesToFetch
Return Value An array of NSPropertyDescription objects that specify which properties should be returned by the fetch. Discussion For a full discussion, see setPropertiesToFetch: (page 115). Availability Available in OS X v10.6 and later. See Also
setPropertiesToFetch: resultType
(page 108)
returnsDistinctResults
Declared in
NSFetchRequest.h
propertiesToGroupBy
Returns an array of objects that indicate how data should be grouped before a select statement is run in an SQL database.
- (NSArray *)propertiesToGroupBy
Return Value An array of NSPropertyDescription or NSExpressionDescription objects, or keypath strings that indicate how data should be grouped before a select statement is run in an SQL database. Discussion For a full description see setPropertiesToGroupBy: (page 116). Availability Available in OS X v10.7 and later. See Also
setPropertiesToGroupBy:
(page 116)
106
setHavingPredicate:
(page 112)
Declared in
NSFetchRequest.h
relationshipKeyPathsForPrefetching
Returns the array of relationship key paths to prefetch along with the entity for the request.
- (NSArray *)relationshipKeyPathsForPrefetching
Return Value The array of relationship key paths to prefetch along with the entity for the request. Discussion The default value is an empty array (no prefetching). Prefetching allows Core Data to obtain related objects in a single fetch (per entity), rather than incurring subsequent access to the store for each individual record as their faults are tripped. For example, given an Employee entity with a relationship to a Department entity, if you fetch all the employees then for each print out their name and the name of the department to which they belong, it may be that a fault has to be fired for each individual Department object (for more details, see Core Data Performance in Core Data Programming Guide ). This can represent a significant overhead. You could avoid this by prefetching the department relationship in the Employee fetch, as illustrated in the following example:
NSManagedObjectContext *context = ...; NSEntityDescription *employeeEntity = [NSEntityDescription entityForName:@"Employee" inManagedObjectContext:context]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:employeeEntity]; [request setRelationshipKeyPathsForPrefetching: [NSArray arrayWithObject:@"department"]];
(page 117)
Declared in
NSFetchRequest.h
107
resultType
Returns the result type of the receiver.
- (NSFetchRequestResultType)resultType
Return Value The result type of the receiver. Discussion The default value is NSManagedObjectResultType. You use setResultType: (page 117) to set the instance type of objects returned from executing the requestfor possible values, see NSFetchRequestResultType (page 121). If you set the value to NSManagedObjectIDResultType, this will demote any sort orderings to best efforts hints if you do not include the property values in the request. Special Considerations See also setIncludesPendingChanges: (page 113) for a discussion the interaction of result type with whether pending changes are taken into account. Availability Available in OS X v10.5 and later. See Also (page 117) setPropertiesToFetch: (page 115) includesPendingChanges (page 102)
setResultType:
Declared in
NSFetchRequest.h
returnsDistinctResults
Returns a Boolean value that indicates whether the fetch request returns only distinct values for the fields specified by propertiesToFetch.
- (BOOL)returnsDistinctResults
Return Value YES if, when the fetch is executed, it returns only distinct values for the fields specified by propertiesToFetch, otherwise NO.
108
Discussion The default value is NO. Special Considerations This value is only used if a value has been set for propertiesToFetch (page 106). Availability Available in OS X v10.6 and later. See Also
setReturnsDistinctResults: propertiesToFetch
(page 118)
(page 106)
Declared in
NSFetchRequest.h
returnsObjectsAsFaults
Returns a Boolean value that indicates whether the objects resulting from a fetch using the receiver are faults.
- (BOOL)returnsObjectsAsFaults
Return Value YES if the objects resulting from a fetch using the receiver are faults, otherwise NO. Discussion The default value is YES. This setting is not used if the result type (see resultType (page 108)) is NSManagedObjectIDResultType, as object IDs do not have property values. You can set returnsObjectsAsFaults to NO to gain a performance benefit if you know you will need to access the property values from the returned objects. By default, when you execute a fetch returnsObjectsAsFaults is YES; Core Data fetches the object data for the matching records, fills the row cache with the information, and returns managed object as faults. These faults are managed objects, but all of their property data resides in the row cache until the fault is fired. When the fault is fired, Core Data retrieves the data from the row cache. Although the overhead for this operation is small, for large datasets it may become non-trivial. If you need to access the property values from the returned objects (for example, if you iterate over all the objects to calculate the average value of a particular attribute), then it is more efficient to set returnsObjectsAsFaults to NO to avoid the additional overhead. Availability Available in OS X v10.5 and later.
109
See Also
setReturnsObjectsAsFaults:
(page 118)
Declared in
NSFetchRequest.h
setAffectedStores:
Sets the array of persistent stores that will be searched by the receiver.
- (void)setAffectedStores:(NSArray *)stores
Parameters
stores
An array containing identifiers for the stores to be searched when the receiver is executed. Availability Available in OS X v10.4 and later. See Also
affectedStores
(page 98)
Declared in
NSFetchRequest.h
setEntity:
Sets the entity of the receiver.
- (void)setEntity:(NSEntityDescription *)entity
Parameters
entity
The entity of the receiver. Availability Available in OS X v10.4 and later. See Also (page 97) initWithEntityName: (page 104) entity (page 99)
+ fetchRequestWithEntityName:
110
Declared in
NSFetchRequest.h
setFetchBatchSize:
Sets the batch size for the receiver.
- (void)setFetchBatchSize:(NSUInteger)bsize
Parameters
bsize
The batch size of the receiver. A batch size of 0 is treated as infinite, which disables the batch faulting behavior. Discussion For a full discussion, see fetchBatchSize (page 100). Availability Available in OS X v10.6 and later. See Also (page 100) fetchLimit (page 100)
fetchBatchSize
Declared in
NSFetchRequest.h
setFetchLimit:
Sets the fetch limit of the receiver.
- (void)setFetchLimit:(NSUInteger)limit
Parameters
limit
The fetch limit of the receiver. 0 specifies no fetch limit. Discussion For a full discussion, see fetchLimit (page 100). Availability Available in OS X v10.4 and later.
111
See Also
fetchLimit fetchOffset
Declared in
NSFetchRequest.h
setFetchOffset:
Sets the fetch offset of the receiver.
- (void)setFetchOffset:(NSUInteger)limit
Parameters
limit
The fetch offset of the receiver. Discussion For a full discussion, see fetchOffset (page 101). Availability Available in OS X v10.6 and later. See Also (page 101) fetchLimit (page 100)
fetchOffset
Declared in
NSFetchRequest.h
setHavingPredicate:
Sets the predicate to use to filter rows being returned by a query containing a GROUP BY.
- (void)setHavingPredicate:(NSPredicate *)predicate
Parameters
predicate
The predicate to use to filter rows being returned by a query containing a GROUP BY.
112
Discussion If a having predicate is supplied, it will be run after the GROUP BY. Specifying a HAVING predicate requires that a GROUP BY also be specified. For a discussion of GROUP BY, see setPropertiesToGroupBy: (page 116). Availability Available in OS X v10.7 and later. See Also (page 102) setPropertiesToGroupBy: (page 116)
havingPredicate
Declared in
NSFetchRequest.h
setIncludesPendingChanges:
Sets if, when the fetch is executed, it matches against currently unsaved changes in the managed object context.
- (void)setIncludesPendingChanges:(BOOL)yesNo
Parameters
yesNo
If YES, when the fetch is executed it will match against currently unsaved changes in the managed object context. Discussion The default value is YES. If the value is NO, the fetch request skips checking unsaved changes and only returns objects that matched the predicate in the persistent store. Special Considerations A value of YES is not supported in conjunction with the result type NSDictionaryResultType (page 122), including calculation of aggregate results (such as max and min). For dictionaries, the array returned from the fetch reflects the current state in the persistent store, and does not take into account any pending changes, insertions, or deletions in the context. If you need to take pending changes into account for some simple aggregations like max and min, you can instead use a normal fetch request, sorted on the attribute you want, with a fetch limit of 1. Availability Available in OS X v10.6 and later.
113
See Also
includesPendingChanges
(page 102)
Declared in
NSFetchRequest.h
setIncludesPropertyValues:
Sets if, when the fetch is executed, property data is obtained from the persistent store.
- (void)setIncludesPropertyValues:(BOOL)yesNo
Parameters
yesNo
If NO, the request will not obtain property information, but only information to identify each object (used to create managed object IDs). Discussion For a full discussion, see includesPropertyValues (page 103). Availability Available in OS X v10.5 and later. See Also
includesPropertyValues
(page 103)
Declared in
NSFetchRequest.h
setIncludesSubentities:
Sets whether the receiver includes subentities.
- (void)setIncludesSubentities:(BOOL)yesNo
Parameters
yesNo
If NO, the receiver will fetch objects of exactly the entity type of the request; if YES, the receiver will include all subentities of the entity for the request (if any). Availability Available in OS X v10.5 and later.
114
See Also
includesSubentities
(page 104)
Declared in
NSFetchRequest.h
setPredicate:
Sets the predicate of the receiver.
- (void)setPredicate:(NSPredicate *)predicate
Parameters
predicate
The predicate for the receiver. Availability Available in OS X v10.4 and later. See Also
predicate
(page 105)
Declared in
NSFetchRequest.h
setPropertiesToFetch:
Specifies which properties should be returned by the fetch.
- (void)setPropertiesToFetch:(NSArray *)values
Parameters
values
An array of NSPropertyDescription objects that specify which properties should be returned by the fetch. Discussion The property descriptions may represent attributes, to-one relationships, or expressions. The name of an attribute or relationship description must match the name of a description on the fetch requests entity. Special Considerations You must set the entity for the fetch request before setting this value, otherwise NSFetchRequest throws an NSInvalidArgumentException exception.
115
This value is only used if resultType (page 108) is set to NSDictionaryResultType (page 122). Availability Available in OS X v10.6 and later. See Also (page 106) resultType (page 108) returnsDistinctResults (page 108)
propertiesToFetch
Declared in
NSFetchRequest.h
setPropertiesToGroupBy:
Sets array of objects that indicate how data should be grouped before a select statement is run in an SQL database.
- (void)setPropertiesToGroupBy:(NSArray *)array
Parameters
array
An array of NSPropertyDescription or NSExpressionDescription objects, or keypath strings that indicate how data should be grouped before a select statement is run in an SQL database. Discussion If you use this setting, then you must set the resultType (page 108) to NSDictionaryResultType (page 122), and the SELECT values must be literals, aggregates, or columns specified in the GROUP BY. Aggregates will operate on the groups specified in the GROUP BY rather than the whole table. If you set properties to group by, you can also set a having predicatesee setHavingPredicate: (page 112). Availability Available in OS X v10.7 and later. See Also (page 106) setHavingPredicate: (page 112)
propertiesToGroupBy
Declared in
NSFetchRequest.h
116
setRelationshipKeyPathsForPrefetching:
Sets an array of relationship key paths to prefetch along with the entity for the request.
- (void)setRelationshipKeyPathsForPrefetching:(NSArray *)keys
Parameters
keys
An array of relationship key-path strings in NSKeyValueCoding notation (as you would normally use with valueForKeyPath:). Discussion For a full discussion, see relationshipKeyPathsForPrefetching (page 107). Availability Available in OS X v10.5 and later. See Also
relationshipKeyPathsForPrefetching
(page 107)
Declared in
NSFetchRequest.h
setResultType:
Sets the result type of the receiver.
- (void)setResultType:(NSFetchRequestResultType)type
Parameters
type
The result type of the receiver. Discussion For further discussion, see resultType (page 108). Availability Available in OS X v10.5 and later. See Also
resultType
(page 108)
Declared in
NSFetchRequest.h
117
setReturnsDistinctResults:
Sets whether the request should return only distinct values for the fields specified by propertiesToFetch.
- (void)setReturnsDistinctResults:(BOOL)values
Parameters
values
If YES, the request returns only distinct values for the fields specified by propertiesToFetch. Discussion For a full discussion, see returnsDistinctResults (page 108). Special Considerations This value is only used if a value has been set for propertiesToFetch. Availability Available in OS X v10.6 and later. See Also (page 108) propertiesToFetch (page 106)
returnsDistinctResults
Declared in
NSFetchRequest.h
setReturnsObjectsAsFaults:
Sets whether the objects resulting from a fetch request are faults.
- (void)setReturnsObjectsAsFaults:(BOOL)yesNo
Parameters
yesNo
If NO, the objects returned from the fetch are pre-populated with their property values (making them fully-faulted objects, which will immediately return NO if sent the isFault (page 163) message). If YES, the objects returned from the fetch are not pre-populated. Discussion For a full discussion, see returnsObjectsAsFaults (page 109). Availability Available in OS X v10.5 and later.
118
See Also
returnsObjectsAsFaults
(page 109)
Declared in
NSFetchRequest.h
setShouldRefreshRefetchedObjects:
Sets whether the fetch request should cause property values of fetched objects to be updated with the current values in the persistent store.
- (void)setShouldRefreshRefetchedObjects:(BOOL)flag
Parameters
flag YES if the fetch request should cause property values of fetched objects to be updated with the current
values in the persistent store, otherwise NO. Discussion By default, when you fetch objects they maintain their current property values, even if the values in the persistent store have changed. By invoking this method with the parameter YES, when the fetch is executed the property values of fetched objects to be updated with the current values in the persistent store. This provides more convenient way to ensure managed object property values are consistent with the store than by using refreshObject:mergeChanges: (page 203) (NSManagedObjetContext) for multiple objects in turn. Availability Available in OS X v10.7 and later. See Also
shouldRefreshRefetchedObjects
(page 120)
Declared in
NSFetchRequest.h
setSortDescriptors:
Sets the array of sort descriptors of the receiver.
- (void)setSortDescriptors:(NSArray *)sortDescriptors
119
Parameters
sortDescriptors
The array of sort descriptors of the receiver. nil specifies no sort descriptors. Availability Available in OS X v10.4 and later. See Also
sortDescriptors
(page 120)
Declared in
NSFetchRequest.h
shouldRefreshRefetchedObjects
Returns a Boolean value that indicates whether the property values of fetched objects will be updated with the current values in the persistent store.
- (BOOL)shouldRefreshRefetchedObjects
Return Value YES if the property values of fetched objects will be updated with the current values in the persistent store, otherwise NO. Discussion For a full discussion, see setShouldRefreshRefetchedObjects: (page 119). Availability Available in OS X v10.7 and later. See Also
setShouldRefreshRefetchedObjects:
(page 119)
Declared in
NSFetchRequest.h
sortDescriptors
Returns the sort descriptors of the receiver.
120
- (NSArray *)sortDescriptors
Return Value The sort descriptors of the receiver. Discussion The sort descriptors specify how the objects returned when the fetch request is issued should be orderedfor example by last name then by first name. The sort descriptors are applied in the order in which they appear in the sortDescriptors array (serially in lowest-array-index-first order). Availability Available in OS X v10.4 and later. See Also
setSortDescriptors:
(page 119)
Declared in
NSFetchRequest.h
Constants
NSFetchRequestResultType
These constants specify the possible result types a fetch request can return.
enum { NSManagedObjectResultType = 0x00, NSManagedObjectIDResultType = 0x01, NSDictionaryResultType = 0x02 NSCountResultType = 0x04 }; typedef NSUInteger NSFetchRequestResultType;
Constants
NSManagedObjectResultType
Specifies that the request returns managed objects. Available in OS X v10.5 and later. Declared in NSFetchRequest.h.
121
NSManagedObjectIDResultType
Specifies that the request returns managed object IDs. Available in OS X v10.5 and later. Declared in NSFetchRequest.h.
NSDictionaryResultType
Specifies that the request returns dictionaries. See also includesPendingChanges (page 102) and setPropertiesToFetch: (page 115). Available in OS X v10.6 and later. Declared in NSFetchRequest.h.
NSCountResultType
Specifies that the request returns the count of the objects that match the request. Available in OS X v10.7 and later. Declared in NSFetchRequest.h. Discussion These constants are used by resultType (page 108).
122
/System/Library/Frameworks/CoreData.framework Available in OS X v10.5 and later. CoreData/NSFetchRequestExpression.h Core Data Programming Guide Predicate Programming Guide
Overview
Instances of NSFetchRequestExpression represent expressions which evaluate to the result of executing a fetch request on a managed object context.
NSFetchRequestExpression inherits from NSExpression, which provides most of the basic behavior. The
first argument must be an expression which evaluates to an NSFetchRequest object, and the second must be an expression which evaluates to an NSManagedObjectContext object. If you simply want the count for the request, the countOnly argument should be YES.
Tasks
Creating a Fetch Request Expression
+ expressionForFetch:context:countOnly:
(page 124) Returns an expression which will evaluate to the result of executing a fetch request on a context.
123
(page 125) Returns the expression for the receivers fetch request. (page 125) Returns the expression for the receivers managed object context. (page 125) Returns a Boolean value that indicates whether the receiver represents a count-only fetch request.
contextExpression
isCountOnlyRequest
Class Methods
expressionForFetch:context:countOnly:
Returns an expression which will evaluate to the result of executing a fetch request on a context.
+ (NSExpression *)expressionForFetch:(NSExpression *)fetch context:(NSExpression
*)context countOnly:(BOOL)countFlag
Parameters
fetch
If YES, when the new expression is evaluated the managed object context (from context) will perform countForFetchRequest:error: (page 189) with the fetch request (from fetch). If NO, when the new expression is evaluated the managed object context will perform executeFetchRequest:error: (page 192) with the fetch request. Return Value An expression which will evaluate to the result of executing a fetch request (from fetch) on a managed object context (from context). Availability Available in OS X v10.5 and later. Declared in
NSFetchRequestExpression.h
124
Instance Methods
contextExpression
Returns the expression for the receivers managed object context.
- (NSExpression *)contextExpression
Return Value The expression for the receivers managed object context. Evaluating the expression must return an NSManagedObjectContext object. Availability Available in OS X v10.5 and later. Declared in
NSFetchRequestExpression.h
isCountOnlyRequest
Returns a Boolean value that indicates whether the receiver represents a count-only fetch request.
- (BOOL)isCountOnlyRequest
Return Value YES if the receiver represents a count-only fetch request, otherwise NO. Discussion If this method returns NO, the managed object context (from the contextExpression (page 125)) will perform executeFetchRequest:error: (page 192): with the requestExpression (page 125); if this method returns YES, the managed object context will perform countForFetchRequest:error: (page 189) with the requestExpression (page 125). Availability Available in OS X v10.5 and later. Declared in
NSFetchRequestExpression.h
requestExpression
Returns the expression for the receivers fetch request.
125
- (NSExpression *)requestExpresson
Return Value The expression for the receivers fetch request. Evaluating the expression must return an NSFetchRequest object. Availability Available in OS X v10.5 and later. Declared in
NSFetchRequestExpression.h
Constants
Fetch request expression type
This constant specifies the fetch request expression type.
enum { NSFetchRequestExpressionType = 50 };
Constants
NSFetchRequestExpressionType
Specifies the fetch request expression type. Available in OS X v10.5 and later. Declared in NSFetchRequestExpression.h. Declared in
NSFetchRequestExpression.h
126
NSPersistentStore : NSObject NSObject (NSObject) /System/Library/Frameworks/CoreData.framework Available in OS X v10.7 and later. NSIncrementalStore.h Incremental Store Programming Guide
Overview
NSIncrementalStore is an abstract superclass defining the API through which Core Data communicates
with a store. This interface is designed to allow you to create persistent stores which load and save data incrementally, allowing for the management of large and/or shared datasets.
Subclassing Notes
Methods to Override
In a subclass of NSIncrementalStore, you must override the following methods to provide behavior appropriate for your store:
loadMetadata: (page 130) executeRequest:withContext:error: (page 129) newValuesForObjectWithID:withContext:error: (page 134) newValueForRelationship:forObjectWithID:withContext:error: (page 133) obtainPermanentIDsForObjects:error: (page 135)
There is no need to override the methods that you must otherwise override for a subclass of NSPersistentStore.
127
Tasks
Required Methods
loadMetadata:
(page 130) Loads the metadata for the store. (page 129) Returns a value as appropriate for the given request, or nil if the request cannot be completed. (page 134) Returns an incremental store node encapsulating the persistent external values of the object with a given object ID. (page 133) Returns the relationship for the given relationship of the object with a given object ID. (page 135) Returns an array containing the object IDs for a given array of newly-inserted objects.
executeRequest:withContext:error:
newValuesForObjectWithID:withContext:error:
newValueForRelationship:forObjectWithID:withContext:error:
obtainPermanentIDsForObjects:error:
Optional Methods
+ identifierForNewStoreAtURL:
(page 129) Returns the identifier for the store at a given URL. (page 131) Indicates that objects identified by a given array of object IDs are in use in a managed object context. (page 131) Indicates that objects identified by a given array of object IDs are no longer being used by a managed object context.
managedObjectContextDidRegisterObjectsWithIDs:
managedObjectContextDidUnregisterObjectsWithIDs:
(page 132) Returns a new object ID that uses given data as the key. (page 135) Returns the reference data used to construct a given object ID.
referenceObjectForObjectID:
128
Class Methods
identifierForNewStoreAtURL:
Returns the identifier for the store at a given URL.
+ (id)identifierForNewStoreAtURL:(NSURL *)storeURL
Parameters
storeURL
The URL of a persistent store. Return Value The identifier for the store at storeURL. Availability Available in OS X v10.7 and later. Declared in
NSIncrementalStore.h
Instance Methods
executeRequest:withContext:error:
Returns a value as appropriate for the given request, or nil if the request cannot be completed.
- (id)executeRequest:(NSPersistentStoreRequest *)request
Parameters
request
A fetch request.
context
If an error occurs, on return contains an NSError object that describes the problem. Return Value A value as appropriate for request, or nil if the request cannot be completed
129
Discussion The value to return depends on the result type (see resultType (page 108)) of request:
If it is NSManagedObjectResultType, NSManagedObjectIDResultType, or NSDictionaryResultType, the method should return an array containing all objects in the store matching the request. If it is NSCountResultType, the method should return an array containing an NSNumber whose value is the count of of all objects in the store matching the request. If the request is a save request, the method should return an empty array.
If the save request contains nil values for the inserted/updated/deleted/locked collections; you should treat it as a request to save the store metadata. You should implement this method conservatively, and expect that unknown request types may at some point be passed to the method. The correct behavior in these cases is to return nil and an error. Availability Available in OS X v10.7 and later. Declared in
NSIncrementalStore.h
loadMetadata:
Loads the metadata for the store.
- (BOOL)loadMetadata:(NSError **)error
Parameters
error
If an error occurs, on return contains an NSError object that describes the problem. Return Value YES if the metadata was correctly loaded, otherwise NO. Discussion In your implementation of this method, you must validate that the URL used to create the store is usable (the location exists and if necessary is writable, the schema is compatible, and so on) and return an error if there is an issue.
130
Any subclass of NSIncrementalStore which is file-based must be able to handle being initialized with a URL pointing to a zero-length file. This serves as an indicator that a new store is to be constructed at the specified location and allows applications using the store to securely create reservation files in known locations. Availability Available in OS X v10.7 and later. Declared in
NSIncrementalStore.h
managedObjectContextDidRegisterObjectsWithIDs:
Indicates that objects identified by a given array of object IDs are in use in a managed object context.
- (void)managedObjectContextDidRegisterObjectsWithIDs:(NSArray *)objectIDs
Parameters
objectIDs
An array of object IDs. Discussion This method and managedObjectContextDidUnregisterObjectsWithIDs: (page 131) allow managed object contexts to communicate interest in the row data of specific objects in a manner akin to reference counting. For more details, see managedObjectContextDidUnregisterObjectsWithIDs: (page 131). Availability Available in OS X v10.7 and later. See Also
managedObjectContextDidUnregisterObjectsWithIDs:
(page 131)
Declared in
NSIncrementalStore.h
managedObjectContextDidUnregisterObjectsWithIDs:
Indicates that objects identified by a given array of object IDs are no longer being used by a managed object context.
- (void)managedObjectContextDidUnregisterObjectsWithIDs:(NSArray *)objectIDs
131
Parameters
objectIDs
An array of object IDs. Discussion This method is the counterpart to managedObjectContextDidRegisterObjectsWithIDs: (page 131). Passing an object ID in the object IDs array of managedObjectContextDidRegisterObjectsWithIDs: is akin to incrementing the object IDs reference count by 1; passing an object ID in the object IDs array of managedObjectContextDidUnregisterObjectsWithIDs: is akin to decrementing the object IDs reference count by 1. It is only when an object IDs reference count is 0 that no contexts indicate that they are using the corresponding managed object. (Object IDs start with a reference count of 0.) For example, if the register methods is invoked on two occasions when the object IDs array contains a given object ID, and the unregister method is invoked once when the object IDs array contains that object ID, then a context is still using the object with the given ID. Availability Available in OS X v10.7 and later. See Also
managedObjectContextDidRegisterObjectsWithIDs:
(page 131)
Declared in
NSIncrementalStore.h
newObjectIDForEntity:referenceObject:
Returns a new object ID that uses given data as the key.
- (NSManagedObjectID *)newObjectIDForEntity:(NSEntityDescription *)entity
referenceObject:(id)data
Parameters
entity
The data to use as the key. Return Value A new object ID for an instance of the entity specified by entity and that uses data as the key.
132
Discussion You should not override this method. Availability Available in OS X v10.7 and later. Declared in
NSIncrementalStore.h
newValueForRelationship:forObjectWithID:withContext:error:
Returns the relationship for the given relationship of the object with a given object ID.
- (id)newValueForRelationship:(NSRelationshipDescription *)relationship
Parameters
relationship
If an error occurs, upon return contains an NSError object that describes the problem. Return Value The value of the relationship specified relationship of the object with object ID objectID, or nil if an error occurs. Discussion If the relationship is a to-one, the method should return an NSManagedObjectID instance that identifies the destination, or an instance of NSNull if the relationship value is nil. If the relationship is a to-many, the method should return a collection object containing NSManagedObjectID instances to identify the related objects. Using an NSArray instance is preferred because it will be the most efficient. A store may also return an instance of NSSet or NSOrderedSet; an instance of NSDictionary is not acceptable. If an object with object ID objectID cannot be found, the method should return nil andif error is not NULLcreate and return an appropriate error object in error.
133
newValuesForObjectWithID:withContext:error:
Returns an incremental store node encapsulating the persistent external values of the object with a given object ID.
- (NSIncrementalStoreNode *)newValuesForObjectWithID:(NSManagedObjectID *)objectID
Parameters
objectID
If an error occurs, upon return contains an NSError object that describes the problem. Return Value An incremental store node encapsulating the persistent external values of the object with object ID objectID, or nil if the corresponding object cannot be found. Discussion The returned node should include all attributes values and may include to-one relationship values as instances of NSManagedObjectID. If an object with object ID objectID cannot be found, the method should return nil andif error is not NULLcreate and return an appropriate error object in error. Availability Available in OS X v10.7 and later. Declared in
NSIncrementalStore.h
134
obtainPermanentIDsForObjects:error:
Returns an array containing the object IDs for a given array of newly-inserted objects.
- (NSArray *)obtainPermanentIDsForObjects:(NSArray *)array error:(NSError **)error
Parameters
array
If an error occurs, upon return contains an NSError object that describes the problem. Return Value An array containing the object IDs for the objects in array. The returned array must return the object IDs in the same order as the objects appear in array. Discussion This method is called before executeRequest:withContext:error: (page 129) with a save request, to assign permanent IDs to newly-inserted objects. Availability Available in OS X v10.7 and later. Declared in
NSIncrementalStore.h
referenceObjectForObjectID:
Returns the reference data used to construct a given object ID.
- (id)referenceObjectForObjectID:(NSManagedObjectID *)objectID
Parameters
objectID
An object ID created by the receiver. Return Value The reference data used to construct objectID. Discussion This method raises an NSInvalidArgumentException if the object ID was not created by the receiving store.
135
You should not override this method. Availability Available in OS X v10.7 and later. Declared in
NSIncrementalStore.h
136
NSObject NSObject (NSObject) /System/Library/Frameworks/CoreData.framework Available in OS X v10.7 and later. NSIncrementalStoreNode.h Incremental Store Programming Guide
Overview
NSIncrementalStoreNode is a concrete class to represent basic nodes in a Core Data incremental store.
A node represents a single record in a persistent store. You can subclass NSIncrementalStoreNode to provide custom behavior.
Tasks
Designated Initializer
initWithObjectID:withValues:version:
(page 139) Returns the object ID that identifies the data stored by the receiver.
137
updateWithValues:version:
(page 139) Update the values and version to reflect new data being saved to or loaded from the external store. (page 140) Returns the value for the given property. (page 140) Return the version of data in the receiver.
valueForPropertyDescription:
version
Instance Methods
initWithObjectID:withValues:version:
Returns an object initialized with the given values.
- (id)initWithObjectID:(NSManagedObjectID *)objectID withValues:(NSDictionary *)values
version:(uint64_t)version
Parameters
objectID
A dictionary containing the values persisted in an external store with keys corresponding to the names of the property description in the NSEntityDescription object described by objectID:
For attributes: an immutable value (an instance of a value class such as NSNumber, NSString, NSData). Missing attribute keys will assume a nil value. For to-one relationships: the managed object ID of the related object or an instance of NSNull for nil relationship values. A missing key will be resolved lazily through calling newValueForRelationship:forObjectWithID:withContext:error: on the NSPersistentStore object. Lazy resolution for to-one relationships is discouraged. For to-many relationships: an instance of NSArray or NSSet containing the managed object IDs of the related objects. Empty to-many relationships must be represented by an empty non-nil collection. A missing key will be resolved lazily through calling newValueForRelationship:forObjectWithID:withContext:error: on the NSPersistentStore object. Lazy resolution for to-many relationships is encouraged.
The revision number of this state. This value is used for conflict detection and merging.
138
Return Value An object initialized with the given values. Discussion Availability Available in OS X v10.7 and later. Declared in
NSIncrementalStoreNode.h
objectID
Returns the object ID that identifies the data stored by the receiver.
- (NSManagedObjectID *)objectID
Return Value The object ID that identifies the data stored by the receiver. Availability Available in OS X v10.7 and later. Declared in
NSIncrementalStoreNode.h
updateWithValues:version:
Update the values and version to reflect new data being saved to or loaded from the external store.
- (void)updateWithValues:(NSDictionary *)values version:(uint64_t)version
Parameters
values
A dictionary containing updated values, in the same format as that described in initWithObjectID:withValues:version: (page 138).
version
The version number for the transaction. Discussion Update the values and version to reflect new data being saved to or loaded from the external store. // The values dictionary is in the same format as the initializer
139
valueForPropertyDescription:
Returns the value for the given property.
- (id)valueForPropertyDescription:(NSPropertyDescription *)prop
Parameters
prop
A property description for one of the properties in the receiver. Return Value The value for the property specified by prop. May return an instance of NSNull for to-one relationships. Discussion If a relationship is nil, you should create a new value by invoking
newValueForRelationship:forObjectWithID:withContext:error: on the NSPersistentStore
version
Return the version of data in the receiver.
- (uint64_t)version
140
141
NSObject NSObject (NSObject) /System/Library/Frameworks/CoreData.framework Available in OS X v10.4 and later. CoreData/NSManagedObject.h Core Data Programming Guide Model Object Implementation Guide Core Data Utility Tutorial
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: (page 161)).
142
Data Storage
In some respects, an NSManagedObject acts like a dictionaryit 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 NSManagedObjectsee Non-Standard Persistent Attributes.
Faulting
Managed objects typically represent data held in a persistent store. In some situations a managed object may be a faultan object whose property values have not yet been loaded from the external data storesee 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 objects 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 Datas behavior.
143
integrated into the Core Data infrastructure. Core Data relies on NSManagedObjects 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:.
initWithEntity:insertIntoManagedObjectContext: didTurnIntoFault
144
willTurnIntoFault dealloc
In addition to methods you should not override, there are others that if you do override you should invoke the superclasss implementation first, including awakeFromInsert, awakeFromFetch, and validation methods. You should not modify relationships in awakeFromFetch (page 151)see the method description for details.
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 scalarsin 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 (page 159) rather than dealloc.
145
Validation Methods
NSManagedObject provides consistent hooks for validating property and inter-property values. You typically
should not override validateValue:forKey:error: (page 175), 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: (page 174) and/or related validation methods. You should not call validateValue:forKey:error: within custom property validation methodsif 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: (page 174)), you should call the superclasss 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 arrayusing the key NSDetailedErrorsKeyto the userInfo dictionary in the NSError object you return. For an example, see Model Object Validation.
Tasks
Initializing a Managed Object
initWithEntity:insertIntoManagedObjectContext:
(page 161) Initializes the receiver and inserts it into the specified managed object context.
(page 159) Returns the entity description of the receiver. (page 166) Returns the object ID of the receiver. (page 169) Returns the receiver.
objectID
self
146
(page 165) Returns the managed object context with which the receiver is registered. (page 160) Returns a Boolean value that indicates whether the receiver has been inserted, has been deleted, or has unsaved changes. (page 164) Returns a Boolean value that indicates whether the receiver has been inserted in a managed object context. (page 165) Returns a Boolean value that indicates whether the receiver has unsaved changes. (page 163) Returns a Boolean value that indicates whether the receiver will be deleted during the next save. (page 163) Returns a Boolean value that indicates whether the receiver is a fault. (page 159) Returns a value that indicates the faulting state of the receiver. (page 161) Returns a Boolean value that indicates whether the relationship for a given key is a fault.
hasChanges
isInserted
isUpdated
isDeleted
isFault
faultingState
hasFaultForRelationshipNamed:
(page 150) Returns a Boolean value that indicates whether instances of the class should be marked as having changes if an unmodeled property is changed. (page 151) Invoked automatically by the Core Data framework after the receiver has been fetched. (page 152) Invoked automatically by the Core Data framework when the receiver is first inserted into a managed object context. (page 152) Invoked automatically by the Core Data framework when the receiver is reset due to an undo, redo, or other multi-property state change.
awakeFromFetch
awakeFromInsert
awakeFromSnapshotEvents:
147
changedValues
(page 153) Returns a dictionary containing the keys and (new) values of persistent properties that have been changed since last fetching or saving the receiver. (page 154) Returns a dictionary containing the keys and (new) values of persistent properties that have changed since the last posting of NSManagedObjectContextObjectsDidChangeNotification. (page 155) Returns a dictionary of the last fetched or saved values of the receiver for the properties specified by the given keys. (page 168) Invoked automatically by the Core Data framework when the receiver is about to be deleted. (page 155) Deallocates the memory occupied by the receiver. (page 178) Invoked automatically by the Core Data framework when the receivers managed object context is saved. (page 158) Invoked automatically by the Core Data framework after the receivers managed object context completes a save operation. (page 179) Invoked automatically by the Core Data framework before receiver is converted to a fault. (page 159) Invoked automatically by the Core Data framework when the receiver is turned into a fault.
changedValuesForCurrentEvent
committedValuesForKeys:
prepareForDeletion
dealloc
willSave
didSave
willTurnIntoFault
didTurnIntoFault
(page 176) Returns the value for the property specified by key. (page 172) Sets the specified property of the receiver to the specified value. (page 166) Returns a mutable set that provides read-write access to the unordered to-many relationship specified by a given key. (page 168) Returns from the receivers private internal storage the value for the specified property.
setValue:forKey:
mutableSetValueForKey:
primitiveValueForKey:
148
setPrimitiveValue:forKey:
(page 170) Sets in the receiver's private internal storage the value of a given property.
Validation
validateValue:forKey:error:
(page 175) Validates a property value for a given key. (page 172) Determines whether the receiver can be deleted in its current state. (page 173) Determines whether the receiver can be inserted in its current state. (page 174) Determines whether the receivers current state is valid.
validateForDelete:
validateForInsert:
validateForUpdate:
(page 150) Returns a Boolean value that indicates whether the receiver provides automatic support for key-value observing change notifications for the given key. (page 156) Provides support for key-value observing access notification. (page 167) Returns the observation info of the receiver. (page 169) Sets the observation info of the receiver. (page 177) Provides support for key-value observing access notification. (page 157) Invoked to inform the receiver that the value of a given property has changed. (page 157) Invoked to inform the receiver that the specified change was made to a specified to-many relationship. (page 177) Invoked to inform the receiver that the value of a given property is about to change.
didAccessValueForKey:
observationInfo
setObservationInfo:
willAccessValueForKey:
didChangeValueForKey:
didChangeValueForKey:withSetMutation:usingObjects:
willChangeValueForKey:
149
willChangeValueForKey:withSetMutation:usingObjects:
(page 178) Invoked to inform the receiver that the specified change is about to be made to a specified to-many relationship.
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.
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)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.
+ (BOOL)contextShouldIgnoreUnmodeledPropertyChanges
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.
150
(page 154)
Declared in
NSManagedObject.h
Instance Methods
awakeFromFetch
Invoked automatically by the Core Data framework after the receiver has been fetched.
- (void)awakeFromFetch
Discussion You typically use this method to compute derived values or to recreate transient relationships from the receivers persistent properties. The managed object contexts 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 supers implementation before performing their own initialization. Availability Available in OS X v10.4 and later. See Also
awakeFromInsert
(page 152)
Declared in
NSManagedObject.h
151
awakeFromInsert
Invoked automatically by the Core Data framework when the receiver is first inserted into a managed object context.
- (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: (page 170) orbetterthe 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 supers implementation before performing their own initialization. Special Considerations If you create a managed object then perform undo operations to bring the managed object context to a state prior to the objects creation, then perform redo operations to bring the managed object context back to a state after the objects 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 OS X v10.4 and later. See Also
awakeFromFetch
awakeFromSnapshotEvents:
Declared in
NSManagedObject.h
awakeFromSnapshotEvents:
Invoked automatically by the Core Data framework when the receiver is reset due to an undo, redo, or other multi-property state change.
152
- (void)awakeFromSnapshotEvents:(NSSnapshotEventType)flags
Parameters
flags
A bitmask of didChangeValueForKey: (page 157) constants to denote the event or events that led to the method being invoked. For possible values, see NSSnapshotEventType (page 180). Discussion You typically use this method to compute derived values or to recreate transient relationships from the receivers 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: (page 170) orbetterthe 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 supers implementation before performing their own initialization. Availability Available in OS X v10.6 and later. See Also
awakeFromFetch awakeFromInsert
Declared in
NSManagedObject.h
changedValues
Returns a dictionary containing the keys and (new) values of persistent properties that have been changed since last fetching or saving the receiver.
- (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.
153
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 OS X v10.4 and later. See Also (page 155) changedValuesForCurrentEvent (page 154)
committedValuesForKeys:
Declared in
NSManagedObject.h
changedValuesForCurrentEvent
Returns a dictionary containing the keys and (new) values of persistent properties that have changed since the last posting of NSManagedObjectContextObjectsDidChangeNotification.
- (NSDictionary *)changedValuesForCurrentEvent
Return Value A dictionary containing as keys the names of persistent properties that have changed since the last posting of NSManagedObjectContextObjectsDidChangeNotification (page 218). 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 OS X v10.7 and later. See Also
changedValues
committedValuesForKeys:
Declared in
NSManagedObject.h
154
committedValuesForKeys:
Returns a dictionary of the last fetched or saved values of the receiver for the properties specified by the given keys.
- (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 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 receivers 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 OS X v10.4 and later. See Also
changedValuesForCurrentEvent
(page 154)
Declared in
NSManagedObject.h
dealloc
Deallocates the memory occupied by the receiver.
- (void)dealloc
155
You should typically not override this methodinstead you should put clean-up code in prepareForDeletion (page 168) or didTurnIntoFault (page 159). See Also (page 168) didTurnIntoFault (page 159)
prepareForDeletion
didAccessValueForKey:
Provides support for key-value observing access notification.
- (void)didAccessValueForKey:(NSString *)key
Parameters
key
The name of one of the receiver's properties. Discussion Together with willAccessValueForKey: (page 177), 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; }
(page 177)
156
Declared in
NSManagedObject.h
didChangeValueForKey:
Invoked to inform the receiver that the value of a given property has changed.
- (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. Availability Available in OS X v10.4 and later. Declared in
NSManagedObject.h
didChangeValueForKey:withSetMutation:usingObjects:
Invoked to inform the receiver that the specified change was made to a specified to-many relationship.
- (void)didChangeValueForKey:(NSString *)inKey
Parameters
inKey
The objects that were involved in the change (see NSKeyValueSetMutationKind). Discussion For more details, see Key-Value Observing Programming Guide .
157
You must not override this method. Availability Available in OS X v10.4 and later. Declared in
NSManagedObject.h
didSave
Invoked automatically by the Core Data framework after the receivers managed object context completes a save operation.
- (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 objects 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 (page 163). Special Considerations You cannot attempt to resurrect a deleted object in didSave. Availability Available in OS X v10.4 and later. See Also
willSave
(page 178)
Declared in
NSManagedObject.h
158
didTurnIntoFault
Invoked automatically by the Core Data framework when the receiver is turned into a fault.
- (void)didTurnIntoFault
Discussion You use this method to clear out custom data cachestransient values declared as entity properties are typically already cleared out by the time this method is invoked (see, for example, refreshObject:mergeChanges: (page 203)). Availability Available in OS X v10.4 and later. See Also
willTurnIntoFault
(page 179)
Declared in
NSManagedObject.h
entity
Returns the entity description of the receiver.
- (NSEntityDescription *)entity
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 OS X v10.4 and later. Declared in
NSManagedObject.h
faultingState
Returns a value that indicates the faulting state of the receiver.
- (NSUInteger)faultingState
159
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 OS X v10.6 and later. See Also
isFault
(page 163)
Declared in
NSManagedObject.h
hasChanges
Returns a Boolean value that indicates whether the receiver has been inserted, has been deleted, or has unsaved changes.
- (BOOL)hasChanges
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 (page 164), isDeleted (page 163), and isUpdated (page 165). Availability Available in OS X v10.7 and later. See Also (page 164) isDeleted (page 163) isUpdated (page 165) isFault (page 163)
isInserted
Declared in
NSManagedObject.h
160
hasFaultForRelationshipNamed:
Returns a Boolean value that indicates whether the relationship for a given key is a fault.
- (BOOL)hasFaultForRelationshipNamed:(NSString *)key
Parameters
key
The name of one of the receivers 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 OS X v10.5 and later. Declared in
NSManagedObject.h
initWithEntity:insertIntoManagedObjectContext:
Initializes the receiver and inserts it into the specified managed object context.
- (id)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.
161
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 (page 152) to be invoked). You are discouraged from overriding this methodyou should instead override awakeFromInsert (page 152) and/or awakeFromFetch (page 151) (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 storesee assignObject:toPersistentStore: (page 188). 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. Special Considerations If you override initWithEntity:insertIntoManagedObjectContext:, you must ensure that you set self to the return value from invocation of supers 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; }
162
See Also
insertNewObjectForEntityForName:inManagedObjectContext: (page 44)
Declared in
NSManagedObject.h
isDeleted
Returns a Boolean value that indicates whether the receiver will be deleted during the next save.
- (BOOL)isDeleted
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 OS X v10.4 and later. See Also (page 163) isInserted (page 164) isUpdated (page 165)
isFault deletedObjects (page 190) (NSManagedObjectContext) NSManagedObjectContextObjectsDidChangeNotification (page 218) (NSManagedObjectContext)
Declared in
NSManagedObject.h
isFault
Returns a Boolean value that indicates whether the receiver is a fault.
- (BOOL)isFault
163
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 OS X v10.4 and later. See Also (page 159) isDeleted (page 163) isInserted (page 164) isUpdated (page 165)
faultingState
Declared in
NSManagedObject.h
isInserted
Returns a Boolean value that indicates whether the receiver has been inserted in a managed object context.
- (BOOL)isInserted
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 OS X v10.4 and later. See Also (page 163) isFault (page 163) isUpdated (page 165)
isDeleted
164
Declared in
NSManagedObject.h
isUpdated
Returns a Boolean value that indicates whether the receiver has unsaved changes.
- (BOOL)isUpdated
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 OS X v10.4 and later. See Also (page 163) isFault (page 163) isInserted (page 164)
isDeleted
Declared in
NSManagedObject.h
managedObjectContext
Returns the managed object context with which the receiver is registered.
- (NSManagedObjectContext *)managedObjectContext
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 OS X v10.4 and later.
165
Declared in
NSManagedObject.h
mutableSetValueForKey:
Returns a mutable set that provides read-write access to the unordered to-many relationship specified by a given key.
- (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 objects generic dictionary storage unless the receivers class explicitly provides key-value coding compliant accessor methods for key. Important: You must not override this method. 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 ). See Also
valueForKey:
(page 176)
objectID
Returns the object ID of the receiver.
- (NSManagedObjectID *)objectID
166
Return Value The object ID of the receiver. Discussion 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. Availability Available in OS X v10.4 and later. See Also
URIRepresentation (page 222) (NSManagedObjectID)
Declared in
NSManagedObject.h
observationInfo
Returns the observation info of the receiver.
- (id)observationInfo
Return Value The observation info of the receiver. Discussion For more about observation information, see Key-Value Observing Programming Guide . Important: You must not override this method. Availability Available in OS X v10.4 and later. See Also
setObservationInfo:
(page 169)
Declared in
NSManagedObject.h
167
prepareForDeletion
Invoked automatically by the Core Data framework when the receiver is about to be deleted.
- (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. Availability Available in OS X v10.6 and later. See Also (page 179) didTurnIntoFault (page 159)
willTurnIntoFault
Declared in
NSManagedObject.h
primitiveValueForKey:
Returns from the receivers private internal storage the value for the specified property.
- (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: (page 177) and didAccessValueForKey: (page 156)). This method is used primarily by subclasses that implement custom accessor methods that need direct access to the receivers private storage. Special Considerations Subclasses should not override this method. The following points also apply:
168
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.
Availability Available in OS X v10.4 and later. See Also (page 169) valueForKey: (page 176) mutableSetValueForKey: (page 166)
setObservationInfo:
Declared in
NSManagedObject.h
self
Returns the receiver.
- (id)self
Discussion Subclasses must not override this method. Note for EOF developers: Core Data does not rely on this method for faultingsee instead willAccessValueForKey: (page 177).
setObservationInfo:
Sets the observation info of the receiver.
- (void)setObservationInfo:(id)value
Parameters
value
169
Discussion For more about observation information, see Key-Value Observing Programming Guide . Availability Available in OS X v10.4 and later. See Also
observationInfo
(page 167)
Declared in
NSManagedObject.h
setPrimitiveValue:forKey:
Sets in the receiver's private internal storage the value of a given property.
- (void)setPrimitiveValue:(id)value forKey:(NSString *)key
Parameters
value
The name of one of the receiver's properties. Discussion Sets in the receivers 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 receivers 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.
170
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 copyas 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 of setPrimitiveValue:newName forKey:@"name"). The dynamic accessors are much more efficient, and allow for compile-time checking.
(page 168)
(page 176)
Declared in
NSManagedObject.h
171
setValue:forKey:
Sets the specified property of the receiver to the specified value.
- (void)setValue:(id)value forKey:(NSString *)key
Parameters
value
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 objects generic dictionary storage unless the receivers class explicitly provides key-value coding compliant accessor methods for key. Important: You must not override this method. Availability Available in OS X v10.4 and later. See Also
valueForKey:
(page 176)
Declared in
NSManagedObject.h
validateForDelete:
Determines whether the receiver can be deleted in its current state.
- (BOOL)validateForDelete:(NSError **)error
172
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 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.
NSManagedObjects implementation sends the receivers entity description a message which performs basic
checking based on the presence or absence of values. Important: Subclasses should invoke supers implementation before performing their own validation, and should combine any error returned by supers implementation with their own (see Model Object Validation). Availability Available in OS X v10.4 and later. See Also (page 173) validateForUpdate: (page 174)
validateForInsert: validateValue:forKey:error:
(page 175)
Declared in
NSManagedObject.h
validateForInsert:
Determines whether the receiver can be inserted in its current state.
- (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.
173
Return Value YES if the receiver can be inserted in its current state, otherwise NO. Special Considerations Subclasses should invoke supers implementation before performing their own validation, and should combine any error returned by supers implementation with their own (see Model Object Validation). Availability Available in OS X v10.4 and later. See Also (page 172) validateForUpdate: (page 174)
validateForDelete: validateValue:forKey:error:
(page 175)
Declared in
NSManagedObject.h
validateForUpdate:
Determines whether the receivers current state is valid.
- (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 YES if the receiver's current state is valid, otherwise NO. Discussion
NSManagedObjects implementation iterates through all of the receivers 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.
174
Important: Subclasses should invoke supers implementation before performing their own validation, and should combine any error returned by supers implementation with their own (see Model Object Validation). Availability Available in OS X v10.4 and later. See Also (page 172) validateForInsert: (page 173)
validateForDelete: validateValue:forKey:error:
(page 175)
Declared in
NSManagedObject.h
validateValue:forKey:error:
Validates a property value for a given key.
- (BOOL)validateValue:(id *)value forKey:(NSString *)key error:(NSError **)error
Parameters
value
A pointer to an object.
key
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 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 objects rules. The default implementation provided by NSManagedObject consults the objects entity description to coerce the value and to check for basic errors, such as a null value when that isnt 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.
175
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: (page 174) and related methods. Availability Available in OS X v10.4 and later. See Also (page 172) validateForInsert: (page 173) validateForUpdate: (page 174)
validateForDelete:
Declared in
NSManagedObject.h
valueForKey:
Returns the value for the property specified by key.
- (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 objects generic dictionary storage unless the receivers class explicitly provides key-value coding compliant accessor methods for key. Important: You must not override this method. Availability Available in OS X v10.4 and later. See Also
primitiveValueForKey:
(page 168)
176
setValue:forKey:
setObservationInfo:
Declared in
NSManagedObject.h
willAccessValueForKey:
Provides support for key-value observing access notification.
- (void)willAccessValueForKey:(NSString *)key
Parameters
key
The name of one of the receiver's properties. Discussion See didAccessValueForKey: (page 156) 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];
(page 156)
Declared in
NSManagedObject.h
willChangeValueForKey:
Invoked to inform the receiver that the value of a given property is about to change.
- (void)willChangeValueForKey:(NSString *)key
Parameters
key
177
Discussion For more details, see Key-Value Observing Programming Guide . You must not override this method. Availability Available in OS X v10.4 and later. Declared in
NSManagedObject.h
willChangeValueForKey:withSetMutation:usingObjects:
Invoked to inform the receiver that the specified change is about to be made to a specified to-many relationship.
- (void)willChangeValueForKey:(NSString *)inKey
Parameters
inKey
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 OS X v10.4 and later. Declared in
NSManagedObject.h
willSave
Invoked automatically by the Core Data framework when the receivers managed object context is saved.
178
- (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 objects 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 its 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 (page 163). Availability Available in OS X v10.4 and later. See Also
didSave
(page 158)
Declared in
NSManagedObject.h
willTurnIntoFault
Invoked automatically by the Core Data framework before receiver is converted to a fault.
- (void)willTurnIntoFault
179
Discussion This method is the companion of the didTurnIntoFault (page 159) 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 OS X v10.5 and later. See Also
didTurnIntoFault
(page 159)
Declared in
NSManagedObject.h
Constants
The following constants relate to errors returned following validation failures.
NSDetailedErrorsKey (page 336)
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. Key for the key that failed to validate for a validation error. For predicate-based validation, key for the predicate for the condition that failed to validate. If non-nil, the key for the value for the key that failed to validate for a validation error.
NSSnapshotEventType
Constants returned from awakeFromSnapshotEvents: (page 152) 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,
180
Constants
NSSnapshotEventUndoInsertion
Specifies a change due to undo from insertion. Available in OS X v10.6 and later. Declared in NSManagedObject.h.
NSSnapshotEventUndoDeletion
Specifies a change due to undo from deletion. Available in OS X v10.6 and later. Declared in NSManagedObject.h.
NSSnapshotEventUndoUpdate
Specifies a change due to a property-level undo. Available in OS X v10.6 and later. Declared in NSManagedObject.h.
NSSnapshotEventRollback
Specifies a change due to the managed object context being rolled back. Available in OS X v10.6 and later. Declared in NSManagedObject.h.
NSSnapshotEventRefresh
Specifies a change due to the managed object being refreshed. Available in OS X v10.6 and later. Declared in NSManagedObject.h.
NSSnapshotEventMergePolicy
Specifies a change due to conflict resolution during a save operation. Available in OS X v10.6 and later. Declared in NSManagedObject.h.
181
/System/Library/Frameworks/CoreData.framework Available in OS X v10.4 and later. NSManagedObjectContext.h Core Data Programming Guide Core Data Utility Tutorial Core Data Snippets Predicate Programming Guide
Overview
An instance of NSManagedObjectContext represents a single object space or scratch pad in an application. Its primary responsibility is to manage a collection of managed objects. These objects form a group of related model objects that represent an internally consistent view of one or more persistent stores. A single managed object instance exists in one and only one context, but multiple copies of an object can exist in different contexts. Thus object uniquing is scoped to a particular context.
Life-cycle Management
The context is a powerful object with a central role in the life-cycle of managed objects, with responsibilities from life-cycle management (including faulting) to validation, inverse relationship handling, and undo/redo. Through a context you can retrieve or fetch objects from a persistent store, make changes to those objects, and then either discard the changes oragain through the contextcommit them back to the persistent
182
store. The context is responsible for watching for changes in its objects and maintains an undo manager so you can have finer-grained control over undo and redo. You can insert new objects and delete ones you have fetched, and commit these modifications to the persistent store.
Parent Store
Prior to OS X v10.7 and iOS v5.0, a context always has a parent persistent store coordinator which provides the model and dispatches requests to the various persistent stores containing the data. Without a coordinator, a context is not fully functional. The contexts coordinator provides the managed object model and handles persistency. In OS X v10.7 and later and iOS v5.0 and later, a context may have a parent context All objects fetched from an external store are registered in a context together with a global identifier (an instance of NSManagedObjectID) thats used to uniquely identify each object to the external store.
Notifications
A context posts notifications at various pointssee
NSManagedObjectContextObjectsDidChangeNotification (page 218) for example. Typically, you should register
Several system frameworks use Core Data internally. If you register to receive these notifications from all contexts (by passing nil as the object parameter to an addObserver method), then you may receive unexpected notifications that are difficult to handle.
Concurrency
Core Data uses thread (or serialized queue) confinement to protect managed objects and managed object contexts (see Concurrency with Core Data). A consequence of this is that a context assumes the default owner is the thread or queue that allocated itthis is determined by the thread that calls its init method. You should not, therefore, initialize a context on one thread then pass it to a different thread. Instead, you should pass a reference to a persistent store coordinator and have the receiving thread/queue create a new context derived from that. If you use NSOperation, you must create the context in main (for a serial queue) or start (for a concurrent queue).
183
In OS X v10.7 and later and iOS v5.0 and later, when you create a context you can specify the concurrency pattern with which you will use it (see initWithConcurrencyType: (page 194)).
Subclassing Notes
You are strongly discouraged from subclassing NSManagedObjectContext. The change tracking and undo management mechanisms are highly optimized and hence intricate and delicate. Interposing your own additional logic that might impact processPendingChanges can have unforeseen consequences. In situations such as store migration, Core Data will create instances of NSManagedObjectContext for its own use. Under these circumstances, you cannot rely on any features of your custom subclass. Any NSManagedObject subclass must always be fully compatible with NSManagedObjectContext (that is, it cannot rely on features of a subclass of NSManagedObjectContext).
Tasks
Registering and Fetching Objects
executeFetchRequest:error:
(page 192) Returns an array of objects that meet the criteria specified by a given fetch request. (page 189) Returns the number of objects a given fetch request would have returned if it had been passed to executeFetchRequest:error:. (page 198) Returns the object for a specified ID, if the object is registered with the receiver. (page 199) Returns the object for a specified ID. (page 193) Returns the object for the specified ID. (page 204) Returns the set of objects registered with the receiver.
countForFetchRequest:error:
objectRegisteredForID:
objectWithID:
existingObjectWithID:error:
registeredObjects
(page 196) Registers an object to be inserted in the receivers persistent store the next time changes are saved.
184
deleteObject:
(page 191) Specifies an object that should be removed from its persistent store when changes are committed. (page 188) Specifies the store in which a newly-inserted object will be saved. (page 199) Converts to permanent IDs the object IDs of the objects in a given array. (page 191) Marks an object for conflict detection. (page 203) Updates the persistent properties of a managed object to use the latest values from the persistent store. (page 202) Forces the receiver to process changes to the object graph. (page 195) Returns the set of objects that have been inserted into the receiver but not yet saved in a persistent store. (page 214) Returns the set of objects registered with the receiver that have uncommitted changes. (page 190) Returns the set of objects that will be removed from their persistent store during the next save operation.
assignObject:toPersistentStore:
obtainPermanentIDsForObjects:error:
detectConflictsForObject:
refreshObject:mergeChanges:
processPendingChanges
insertedObjects
updatedObjects
deletedObjects
Managing Concurrency
initWithConcurrencyType:
(page 194) Initializes a context with a given concurrency type. (page 189) Returns the concurrency type for the receiver. (page 197) Merges the changes specified in a given notification.
concurrencyType
mergeChangesFromContextDidSaveNotification:
Undo Management
undoManager
(page 213) Returns the undo manager of the receiver. (page 211) Sets the undo manager of the receiver.
setUndoManager:
185
undo
(page 212) Sends an undo message to the receivers undo manager, asking it to reverse the latest uncommitted changes applied to objects in the object graph. (page 203) Sends an redo message to the receivers undo manager, asking it to reverse the latest undo operation applied to objects in the object graph. (page 205) Returns the receiver to its base state. (page 206) Removes everything from the undo stack, discards all insertions and deletions, and restores updated objects to their last committed values. (page 206) Attempts to commit unsaved changes to registered objects to their persistent store. (page 194) Returns a Boolean value that indicates whether the receiver has uncommitted changes.
redo
reset
rollback
save:
hasChanges
(page 201) Returns the persistent store coordinator of the receiver. (page 208) Sets the persistent store coordinator of the receiver. (page 200) Returns the receivers parent context. (page 207) Sets the receivers parent context to the given context.
setPersistentStoreCoordinator:
parentContext
setParentContext:
Locking
lock
(page 196) Attempts to acquire a lock on the receiver. (page 213) Relinquishes a previously acquired lock.
unlock
186
tryLock
Delete Propagation
propagatesDeletesAtEndOfEvent
(page 202) Returns a Boolean that indicates whether the receiver propagates deletes at the end of the event in which a change was made. (page 209) Sets whether the context propagates deletes to related objects at the end of the event.
setPropagatesDeletesAtEndOfEvent:
Registered Objects
retainsRegisteredObjects
(page 205) Returns a Boolean that indicates whether the receiver keeps strong references to all registered managed objects. (page 209) Sets whether the receiver keeps strong references to all registered managed objects, or only objects necessary for a pending save (those that are inserted, updated, deleted, or locked).
setRetainsRegisteredObjects:
(page 211) Returns the maximum length of time that may have elapsed since the store previously fetched data before fulfilling a fault issues a new fetch rather than using the previously-fetched data. (page 210) Sets the maximum length of time that may have elapsed since the store previously fetched data before fulfilling a fault issues a new fetch rather than using the previously-fetched data.
setStalenessInterval:
(page 198) Returns the merge policy of the receiver. (page 207) Sets the merge policy of the receiver.
setMergePolicy:
187
performBlockAndWait:
User Info
userInfo
Instance Methods
assignObject:toPersistentStore:
Specifies the store in which a newly-inserted object will be saved.
- (void)assignObject:(id)object toPersistentStore:(NSPersistentStore *)store
Parameters
object
A managed object.
store
A persistent store. Discussion You can obtain a store from the persistent store coordinator, using for example persistentStoreForURL: (page 286). Special Considerations It is only necessary to use this method if the receivers persistent store coordinator manages multiple writable stores that have objects entity in their configuration. Maintaining configurations in the managed object model can eliminate the need for invoking this method directly in many situations. If the receivers persistent store coordinator manages only a single writable store, or if only one store has objects entity in its model, object will automatically be assigned to that store.
188
persistentStoreCoordinator
Declared in
NSManagedObjectContext.h
concurrencyType
Returns the concurrency type for the receiver.
- (NSManagedObjectContextConcurrencyType)concurrencyType
Return Value The concurrency type for the receiver. Discussion Availability Available in OS X v10.7 and later. See Also
initWithConcurrencyType:
(page 194)
Declared in
NSManagedObjectContext.h
countForFetchRequest:error:
Returns the number of objects a given fetch request would have returned if it had been passed to executeFetchRequest:error:.
- (NSUInteger)countForFetchRequest:(NSFetchRequest *)request error:(NSError **)error
Parameters
request
A fetch request that specifies the search criteria for the fetch.
error
If there is a problem executing the fetch, upon return contains an instance of NSError that describes the problem.
189
Return Value The number of objects a given fetch request would have returned if it had been passed to executeFetchRequest:error: (page 192), or NSNotFound if an error occurs. Availability Available in OS X v10.5 and later. Declared in
NSManagedObjectContext.h
deletedObjects
Returns the set of objects that will be removed from their persistent store during the next save operation.
- (NSSet *)deletedObjects
Return Value The set of objects that will be removed from their persistent store during the next save operation. Discussion The returned set does not necessarily include all the objects that have been deleted (using deleteObject: (page 191))if an object has been inserted and deleted without an intervening save operation, it is not included in the set. A managed object context does not post key-value observing notifications when the return value of deletedObjects changes. A context does, however, post a NSManagedObjectContextObjectsDidChangeNotification (page 218) notification when a change is made, and a NSManagedObjectContextWillSaveNotification (page 219) notification and a NSManagedObjectContextDidSaveNotification (page 218) notification before and after changes are committed respectively (although again the set of deleted objects given for a NSManagedObjectContextDidSaveNotification (page 218) does not include objects that were inserted and deleted without an intervening save operationthat is, they had never been saved to a persistent store). Availability Available in OS X v10.4 and later. See Also (page 191) insertedObjects (page 195) registeredObjects (page 204) updatedObjects (page 214) isDeleted (page 163) (NSManagedObject)
deleteObject:
190
Declared in
NSManagedObjectContext.h
deleteObject:
Specifies an object that should be removed from its persistent store when changes are committed.
- (void)deleteObject:(NSManagedObject *)object
Parameters
object
A managed object. Discussion When changes are committed, object will be removed from the uniquing tables. If object has not yet been saved to a persistent store, it is simply removed from the receiver. Availability Available in OS X v10.4 and later. See Also (page 190) isDeleted (page 163) (NSManagedObject)
deletedObjects
Declared in
NSManagedObjectContext.h
detectConflictsForObject:
Marks an object for conflict detection.
- (void)detectConflictsForObject:(NSManagedObject *)object
Parameters
object
A managed object. Discussion If on the next invocation of save: (page 206) object has been modified in its persistent store, the save fails. This allows optimistic locking for unchanged objects. Conflict detection is always performed on changed or deleted objects.
191
executeFetchRequest:error:
Returns an array of objects that meet the criteria specified by a given fetch request.
- (NSArray *)executeFetchRequest:(NSFetchRequest *)request error:(NSError **)error
Parameters
request
A fetch request that specifies the search criteria for the fetch.
error
If there is a problem executing the fetch, upon return contains an instance of NSError that describes the problem. Return Value An array of objects that meet the criteria specified by request fetched from the receiver and from the persistent stores associated with the receivers persistent store coordinator. If an error occurs, returns nil. If no objects match the criteria specified by request, returns an empty array. Discussion Returned objects are registered with the receiver. The following points are important to consider:
If the fetch request has no predicate, then all instances of the specified entity are retrieved, modulo other criteria below. An object that meets the criteria specified by request (it is an instance of the entity specified by the request, and it matches the requests predicate if there is one) and that has been inserted into a context but which is not yet saved to a persistent store, is retrieved if the fetch request is executed on that context. If an object in a context has been modified, a predicate is evaluated against its modified state, not against the current state in the persistent store. Therefore, if an object in a context has been modified such that it meets the fetch requests criteria, the request retrieves it even if changes have not been saved to the store and the values in the store are such that it does not meet the criteria. Conversely, if an object in a context has been modified such that it does not match the fetch request, the fetch request will not retrieve it even if the version in the store does match.
192
If an object has been deleted from the context, the fetch request does not retrieve it even if that deletion has not been saved to a store.
Objects that have been realized (populated, faults fired, read from , and so on) as well as pending updated, inserted, or deleted, are never changed by a fetch operation without developer intervention. If you fetch some objects, work with them, and then execute a new fetch that includes a superset of those objects, you do not get new instances or update data for the existing objectsyou get the existing objects with their current in-memory state. Availability Available in OS X v10.4 and later.
Related Sample Code Core Data Utility
Declared in
NSManagedObjectContext.h
existingObjectWithID:error:
Returns the object for the specified ID.
- (NSManagedObject *)existingObjectWithID:(NSManagedObjectID *)objectID error:(NSError
**)error
Parameters
objectID
If there is a problem in retrieving the object specified by objectID, upon return contains an error that describes the problem. Return Value The object specified by objectID. If the object cannot be fetched, or does not exist, or cannot be faulted, it returns nil. Discussion If there is a managed object with the given ID already registered in the context, that object is returned directly; otherwise the corresponding object is faulted into the context. This method might perform I/O if the data is uncached. Unlike objectWithID: (page 199), this method never returns a fault.
193
objectRegisteredForID:
Declared in
NSManagedObjectContext.h
hasChanges
Returns a Boolean value that indicates whether the receiver has uncommitted changes.
- (BOOL)hasChanges
Return Value YES if the receiver has uncommitted changes, otherwise NO. Discussion In OS X v10.6 and later, this property is key-value observing compliant. Special Considerations If you are observing this property using key-value observing (KVO) you should not touch the context or its objects within your implementation of observeValueForKeyPath:ofObject:change:context: for this notification. (This is because of the intricacy of the locations of the KVO notificationsfor example, the context may be in the middle of an undo operation, or repairing a merge conflict.) If you need to send messages to the context or change any of its managed objects as a result of a change to the value of hasChanges, you must do so after the call stack unwinds (typically using performSelector:withObject:afterDelay: or a similar method). Availability Available in OS X v10.4 and later. Declared in
NSManagedObjectContext.h
initWithConcurrencyType:
Initializes a context with a given concurrency type.
- (id)initWithConcurrencyType:(NSManagedObjectContextConcurrencyType)ct
194
Parameters
ct
The concurrency pattern with which context will be used. Return Value A context initialized to use the given concurrency type. Discussion Availability Available in OS X v10.7 and later. See Also
concurrencyType
(page 189)
Declared in
NSManagedObjectContext.h
insertedObjects
Returns the set of objects that have been inserted into the receiver but not yet saved in a persistent store.
- (NSSet *)insertedObjects
Return Value The set of objects that have been inserted into the receiver but not yet saved in a persistent store. Discussion A managed object context does not post key-value observing notifications when the return value of insertedObjects changesit does, however, post a NSManagedObjectContextObjectsDidChangeNotification (page 218) notification when a change is made, and a NSManagedObjectContextWillSaveNotification (page 219) and a NSManagedObjectContextDidSaveNotification (page 218) notification before and after changes are committed respectively. Availability Available in OS X v10.4 and later. See Also (page 190) insertObject: (page 196)
deletedObjects
195
Declared in
NSManagedObjectContext.h
insertObject:
Registers an object to be inserted in the receivers persistent store the next time changes are saved.
- (void)insertObject:(NSManagedObject *)object
Parameters
object
A managed object. Discussion The managed object (object) is registered in the receiver with a temporary global ID. It is assigned a permanent global ID when changes are committed. If the current transaction is rolled back (for example, if the receiver is sent a rollback (page 206) message) before a save operation, the object is unregistered from the receiver. Availability Available in OS X v10.4 and later. See Also
insertedObjects
(page 195)
Declared in
NSManagedObjectContext.h
lock
Attempts to acquire a lock on the receiver.
- (void)lock
Discussion This method blocks a threads execution until the lock can be acquired. An application protects a critical section of code by requiring a thread to acquire a lock before executing the code. Once the critical section is past, the thread relinquishes the lock by invoking unlock (page 213).
196
Sending this message to a managed object context helps the framework to understand the scope of a transaction in a multi-threaded environment. It is preferable to use the NSManagedObjectContexts implementation of NSLocking instead using of a separate mutex object. If you lock (or successfully tryLock) a managed object context, the thread in which the lock call is made must keep a strong reference to the context until it invokes unlock, otherwise if the context is deallocated this will result in deadlock. Availability Available in OS X v10.4 and later. See Also (page 212) unlock (page 213)
tryLock
Declared in
NSManagedObjectContext.h
mergeChangesFromContextDidSaveNotification:
Merges the changes specified in a given notification.
- (void)mergeChangesFromContextDidSaveNotification:(NSNotification *)notification
Parameters
notification
An instance of an NSManagedObjectContextDidSaveNotification (page 218) notification posted by another context. Discussion This method refreshes any objects which have been updated in the other context, faults in any newly-inserted objects, and invokes deleteObject: (page 191): on those which have been deleted. You can pass a NSManagedObjectContextDidSaveNotification notification posted by a managed object context on another thread, however you must not use the managed objects in the user info dictionary directly. For more details, see Concurrency with Core Data. Availability Available in OS X v10.5 and later. Declared in
NSManagedObjectContext.h
197
mergePolicy
Returns the merge policy of the receiver.
- (id)mergePolicy
Return Value The receivers merge policy. Discussion The default is NSErrorMergePolicy. Availability Available in OS X v10.4 and later. Declared in
NSManagedObjectContext.h
objectRegisteredForID:
Returns the object for a specified ID, if the object is registered with the receiver.
- (NSManagedObject *)objectRegisteredForID:(NSManagedObjectID *)objectID
Parameters
objectID
An object ID. Return Value The object for the specified ID if it is registered with the receiver, otherwise nil. Availability Available in OS X v10.4 and later. See Also
objectWithID:
existingObjectWithID:error:
Declared in
NSManagedObjectContext.h
198
objectWithID:
Returns the object for a specified ID.
- (NSManagedObject *)objectWithID:(NSManagedObjectID *)objectID
Parameters
objectID
An object ID. Return Value The object for the specified ID. Discussion If the object is not registered in the context, it may be fetched or returned as a fault. This method always returns an object. The data in the persistent store represented by objectID is assumed to existif it does not, the returned object throws an exception when you access any property (that is, when the fault is fired). The benefit of this behavior is that it allows you to create and use faults, then create the underlying rows later or in a separate context. Availability Available in OS X v10.4 and later. See Also (page 198) existingObjectWithID:error: (page 193)
objectRegisteredForID: managedObjectIDForURIRepresentation: (page 283) URIRepresentation (page 222)
Declared in
NSManagedObjectContext.h
obtainPermanentIDsForObjects:error:
Converts to permanent IDs the object IDs of the objects in a given array.
- (BOOL)obtainPermanentIDsForObjects:(NSArray *)objects error:(NSError **)error
Parameters
objects
If an error occurs, upon return contains an NSError object that describes the problem.
199
Return Value YES if permanent IDs are obtained for all the objects in objects, otherwise NO. Discussion This method converts the object ID of each managed object in objects to a permanent ID. Although the object will have a permanent ID, it will still respond positively to isInserted (page 164) until it is saved. Any object that already has a permanent ID is ignored. Any object not already assigned to a store is assigned based on the same rules Core Data uses for assignment during a save operation (first writable store supporting the entity, and appropriate for the instance and its related items). Special Considerations This method results in a transaction with the underlying store which changes the files modification date. In OS X, this results an additional consideration if you invoke this method on the managed object context associated with an instance of NSPersistentDocument. Instances of NSDocument need to know that they are in sync with the underlying content. To avoid problems, after invoking this method you must therefore update the documents modification date (using setFileModificationDate:). Availability Available in OS X v10.5 and later. Declared in
NSManagedObjectContext.h
parentContext
Returns the receivers parent context.
- (NSManagedObjectContext *)parentContext
Return Value The receivers parent context, or nil if it doesnt have a parent context. Discussion Availability Available in OS X v10.7 and later. See Also
setParentContext:
persistentStoreCoordinator
200
Declared in
NSManagedObjectContext.h
performBlock:
- (void)performBlock:(void (^)())block
Parameters
block
The block to perform. Discussion Availability Available in OS X v10.7 and later. Declared in
NSManagedObjectContext.h
performBlockAndWait:
- (void)performBlockAndWait:(void (^)())block
Parameters
block
The block to perform. Discussion Availability Available in OS X v10.7 and later. Declared in
NSManagedObjectContext.h
persistentStoreCoordinator
Returns the persistent store coordinator of the receiver.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
201
Return Value The persistent store coordinator of the receiver. Availability Available in OS X v10.4 and later. Declared in
NSManagedObjectContext.h
processPendingChanges
Forces the receiver to process changes to the object graph.
- (void)processPendingChanges
Discussion This method causes changes to registered managed objects to be recorded with the undo manager. In AppKit-based applications, this method is invoked automatically at least once during the event loop (at the end of the loop)it may be called more often than that if the framework needs to coalesce your changes before doing something else. You can also invoke it manually to coalesce any pending unprocessed changes. Availability Available in OS X v10.4 and later. See Also redo (page 203) undo (page 212) undoManager (page 213) Declared in
NSManagedObjectContext.h
propagatesDeletesAtEndOfEvent
Returns a Boolean that indicates whether the receiver propagates deletes at the end of the event in which a change was made.
- (BOOL)propagatesDeletesAtEndOfEvent
202
Return Value YES if the receiver propagates deletes at the end of the event in which a change was made, NO if it propagates deletes only immediately before saving changes. Availability Available in OS X v10.4 and later. See Also
setPropagatesDeletesAtEndOfEvent:
(page 209)
Declared in
NSManagedObjectContext.h
redo
Sends an redo message to the receivers undo manager, asking it to reverse the latest undo operation applied to objects in the object graph.
- (void)redo
Availability Available in OS X v10.4 and later. See Also undo (page 212)
processPendingChanges
(page 202)
Declared in
NSManagedObjectContext.h
refreshObject:mergeChanges:
Updates the persistent properties of a managed object to use the latest values from the persistent store.
- (void)refreshObject:(NSManagedObject *)object mergeChanges:(BOOL)flag
Parameters
object
A managed object.
203
flag
A Boolean value. If flag is NO, then object is turned into a fault and any pending changes are lost. The object remains a fault until it is accessed again, at which time its property values will be reloaded from the store or last cached state. If flag is YES, then objects property values are reloaded from the values from the store or the last cached state then any changes that were made (in the local context) are re-applied over those (now newly updated) values. (If flag is YES the merge of the values into object will always succeedin this case there is therefore no such thing as a merge conflict or a merge that is not possible.) Discussion If the staleness interval (see stalenessInterval (page 211)) has not been exceeded, any available cached data is reused instead of executing a new fetch. If flag is YES, this method does not affect any transient properties; if flag is NO, transient properties are disposed of. You typically use this method to ensure data freshness if more than one managed object context may use the same persistent store simultaneously, in particular if you get an optimistic locking failure when attempting to save. Turning object into a fault (flag is NO) means that strong references to related managed objects (that is, those to which object has a reference) are broken, so you can also use this method to trim a portion of your object graph you want to constrain memory usage. Availability Available in OS X v10.4 and later. See Also
detectConflictsForObject: reset
(page 191)
setStalenessInterval:
Declared in
NSManagedObjectContext.h
registeredObjects
Returns the set of objects registered with the receiver.
- (NSSet *)registeredObjects
204
Return Value The set of objects registered with the receiver. Discussion A managed object context does not post key-value observing notifications when the return value of registeredObjects changes. Availability Available in OS X v10.4 and later. See Also (page 190) (page 195) updatedObjects (page 214)
deletedObjects insertedObjects
Declared in
NSManagedObjectContext.h
reset
Returns the receiver to its base state.
- (void)reset
Discussion All the receiver's managed objects are forgotten. If you use this method, you should ensure that you also discard references to any managed objects fetched using the receiver, since they will be invalid afterwards. Availability Available in OS X v10.4 and later. See Also
rollback undo
setStalenessInterval:
(page 212)
Declared in
NSManagedObjectContext.h
retainsRegisteredObjects
Returns a Boolean that indicates whether the receiver keeps strong references to all registered managed objects.
205
- (BOOL)retainsRegisteredObjects
Return Value YES if the receiver keeps strong references to all registered managed objects, otherwise NO. Availability Available in OS X v10.4 and later. See Also
setRetainsRegisteredObjects:
(page 209)
Declared in
NSManagedObjectContext.h
rollback
Removes everything from the undo stack, discards all insertions and deletions, and restores updated objects to their last committed values.
- (void)rollback
Discussion This method does not refetch data from the persistent store or stores. Availability Available in OS X v10.4 and later. See Also reset (page 205)
setStalenessInterval: undo
(page 212)
processPendingChanges
Declared in
NSManagedObjectContext.h
save:
Attempts to commit unsaved changes to registered objects to their persistent store.
- (BOOL)save:(NSError **)error
206
Parameters
error
A pointer to an NSError object. You do not need to create an NSError object. The save operation aborts after the first failure if you pass NULL. Return Value YES if the save succeeds, otherwise NO. Discussion If there were multiple errors (for example several edited objects had validation failures) the description of NSError returned indicates that there were multiple errors, and its userInfo dictionary contains the key NSDetailedErrors. The value associated with the NSDetailedErrors key is an array that contains the individual NSError objects. Availability Available in OS X v10.4 and later. Declared in
NSManagedObjectContext.h
setMergePolicy:
Sets the merge policy of the receiver.
- (void)setMergePolicy:(id)mergePolicy
Parameters
mergePolicy
The merge policy of the receiver. For possible values, see NSMergePolicy. Availability Available in OS X v10.4 and later. Declared in
NSManagedObjectContext.h
setParentContext:
Sets the receivers parent context to the given context.
- (void)setParentContext:(NSManagedObjectContext *)parent
207
Parameters
parent
The parent context for the receiver. Discussion Availability Available in OS X v10.7 and later. See Also
parentContext
setPersistentStoreCoordinator:
Declared in
NSManagedObjectContext.h
setPersistentStoreCoordinator:
Sets the persistent store coordinator of the receiver.
- (void)setPersistentStoreCoordinator:(NSPersistentStoreCoordinator *)coordinator
Parameters
coordinator
The persistent store coordinator of the receiver. Discussion The coordinator provides the managed object model and handles persistency. Note that multiple contexts can share a coordinator. This method raises an exception if coordinator is nil. If you want to disconnect" a context from its persistent store coordinator, you should simply set all strong references to the context to nil and allow it to be deallocated normally. Availability Available in OS X v10.4 and later.
Related Sample Code Core Data Utility
Declared in
NSManagedObjectContext.h
208
setPropagatesDeletesAtEndOfEvent:
Sets whether the context propagates deletes to related objects at the end of the event.
- (void)setPropagatesDeletesAtEndOfEvent:(BOOL)flag
Parameters
Flag
A Boolean value that indicates whether the context propagates deletes to related objects at the end of the event (YES) or not (NO). Discussion The default is YES. If the value is NO, then deletes are propagated during a save operation. Availability Available in OS X v10.4 and later. See Also
propagatesDeletesAtEndOfEvent
(page 202)
Declared in
NSManagedObjectContext.h
setRetainsRegisteredObjects:
Sets whether the receiver keeps strong references to all registered managed objects, or only objects necessary for a pending save (those that are inserted, updated, deleted, or locked).
- (void)setRetainsRegisteredObjects:(BOOL)flag
Parameters
flag
A Boolean value. If flag is NO, then the receiver keeps strong references to registered objects only when they are inserted, updated, deleted, or locked. If flag is YES, the receiver keeps strong references to all registered managed objects. Discussion The default is NO. Availability Available in OS X v10.4 and later.
209
See Also
retainsRegisteredObjects
(page 205)
Declared in
NSManagedObjectContext.h
setStalenessInterval:
Sets the maximum length of time that may have elapsed since the store previously fetched data before fulfilling a fault issues a new fetch rather than using the previously-fetched data.
- (void)setStalenessInterval:(NSTimeInterval)expiration
Parameters
expiration
The maximum length of time that may have elapsed since the store previously fetched data before fulfilling a fault issues a new fetch rather than using the previously-fetched data. A negative value represents an infinite value; 0.0 represents no staleness acceptable . Discussion The staleness interval controls whether fulfilling a fault uses data previously fetched by the application, or issues a new fetch (see also refreshObject:mergeChanges: (page 203)). The staleness interval does not affect objects currently in use (that is, it is not used to automatically update property values from a persistent store after a certain period of time). The expiration value is applied on a per object basis. It is the relative time until cached data (snapshots) should be considered stale. For example, a value of 300.0 informs the context to utilize cached information for no more than 5 minutes after an object was originally fetched. Note that the staleness interval is a hint and may not be supported by all persistent store types. It is not used by XML and binary stores, since these stores maintain all current values in memory. Availability Available in OS X v10.4 and later. See Also reset (page 205) rollback (page 206)
stalenessInterval undo
(page 212)
refreshObject:mergeChanges:
210
Declared in
NSManagedObjectContext.h
setUndoManager:
Sets the undo manager of the receiver.
- (void)setUndoManager:(NSUndoManager *)undoManager
Parameters
undoManager
The undo manager of the receiver. Discussion You can set the undo manager to nil to disable undo support. This provides a performance benefit if you do not want to support undo for a particular context, for example in a large import processsee Core Data Programming Guide . If a context does not have an undo manager, you can enable undo support by setting one. You may also replace a contexts undo manager if you want to integrate the contexts undo operations with another undo manager in your application. Important: In OS X, a context provides an undo manager by default; on iOS, the undo manager is nil by default. Availability Available in OS X v10.4 and later. Declared in
NSManagedObjectContext.h
stalenessInterval
Returns the maximum length of time that may have elapsed since the store previously fetched data before fulfilling a fault issues a new fetch rather than using the previously-fetched data.
- (NSTimeInterval)stalenessInterval
Return Value The maximum length of time that may have elapsed since the store previously fetched data before fulfilling a fault issues a new fetch rather than using the previously-fetched data.
211
Discussion The default is infinite staleness, represented by an interval of -1 (although any negative value represents an infinite value); 0.0 represents no staleness acceptable . For a full discussion, see setStalenessInterval: (page 210). Availability Available in OS X v10.4 and later. See Also
setStalenessInterval:
(page 210)
Declared in
NSManagedObjectContext.h
tryLock
Attempts to acquire a lock.
- (BOOL)tryLock
Return Value YES if a lock was acquired, NO otherwise. Discussion This method returns immediately after the attempt to acquire a lock. Availability Available in OS X v10.4 and later. See Also lock (page 196) unlock (page 213) Declared in
NSManagedObjectContext.h
undo
Sends an undo message to the receivers undo manager, asking it to reverse the latest uncommitted changes applied to objects in the object graph.
212
- (void)undo
Availability Available in OS X v10.4 and later. See Also reset (page 205) rollback (page 206) undoManager (page 213)
processPendingChanges
(page 202)
Declared in
NSManagedObjectContext.h
undoManager
Returns the undo manager of the receiver.
- (NSUndoManager *)undoManager
Return Value The undo manager of the receiver. Discussion For a discussion, see setUndoManager: (page 211). Important: In OS X, a context provides an undo manager by default; on iOS, the undo manager is nil by default. Availability Available in OS X v10.4 and later. Declared in
NSManagedObjectContext.h
unlock
Relinquishes a previously acquired lock.
- (void)unlock
213
updatedObjects
Returns the set of objects registered with the receiver that have uncommitted changes.
- (NSSet *)updatedObjects
Return Value The set of objects registered with the receiver that have uncommitted changes. Discussion A managed object context does not post key-value observing notifications when the return value of updatedObjects changes. A context does, however, post a NSManagedObjectContextObjectsDidChangeNotification (page 218) notification when a change is made, and a NSManagedObjectContextWillSaveNotification (page 219) notification and a NSManagedObjectContextDidSaveNotification (page 218) notification before and after changes are committed respectively. Availability Available in OS X v10.4 and later. See Also (page 190) insertedObjects (page 195) registeredObjects (page 204)
deletedObjects
Declared in
NSManagedObjectContext.h
userInfo
Returns the receivers user info.
- (NSMutableDictionary *)userInfo
214
Return Value The receivers user info. Discussion Availability Available in OS X v10.7 and later. Declared in
NSManagedObjectContext.h
Constants
NSManagedObjectContext Change Notification User Info Keys
Core Data uses these string constants as keys in the user info dictionary in aNSManagedObjectContextObjectsDidChangeNotification (page 218) notification.
* * * * * *
Constants
NSInsertedObjectsKey
Key for the set of objects that were inserted into the context. Available in OS X v10.4 and later. Declared in NSManagedObjectContext.h.
NSUpdatedObjectsKey
Key for the set of objects that were updated. Available in OS X v10.4 and later. Declared in NSManagedObjectContext.h.
NSDeletedObjectsKey
Key for the set of objects that were marked for deletion during the previous event. Available in OS X v10.4 and later. Declared in NSManagedObjectContext.h.
215
NSRefreshedObjectsKey
Key for the set of objects that were refreshed. Available in OS X v10.5 and later. Declared in NSManagedObjectContext.h.
NSInvalidatedObjectsKey
Key for the set of objects that were invalidated. Available in OS X v10.5 and later. Declared in NSManagedObjectContext.h.
NSInvalidatedAllObjectsKey
Key that specifies that all objects in the context have been invalidated. Available in OS X v10.5 and later. Declared in NSManagedObjectContext.h.
The following constants, defined in CoreDataErrors.h, relate to errors returned following validation failures or problems encountered during a save operation.
NSValidationObjectErrorKey (page 337)
Key for the object that failed to validate for a validation error. The key for stores prompting an error. The key for objects prompting an error.
NSAffectedObjectsErrorKey
Each conflict record in the @"conflictList" array in the userInfo dictionary for an error from the NSErrorMergePolicy is a dictionary containing some of the keys described in the following table. Of the cachedRow, databaseRow, and snapshot keys, only two will be present depending on whether the conflict is between the managed object context and the persistent store coordinator (snapshot and cachedRow) or between the persistent store coordinator and the persistent store (cachedRow and databaseRow).
Constant Description
@"object" @"snapshot"
The managed object that could not be saved. A dictionary of key-value pairs for the properties that represents the managed object contexts last saved state for this managed object. A dictionary of key-value pairs for the properties that represents the persistent store's last saved state for this managed object.
@"cachedRow"
216
Constant
Description
@"databaseRow" A dictionary of key-value pairs for the properties that represents the database's current
An NSNumber object whose value is latest version number of this managed object. As NSNumber object whose value is the version number that this managed object context last saved for this managed object.
NSManagedObjectContextConcurrencyType
Constants to indicate the concurrency pattern with which a context will be used.
enum { NSConfinementConcurrencyType = 0x00, NSPrivateQueueConcurrencyType = 0x01, NSMainQueueConcurrencyType = 0x02 }; typedef NSUInteger NSManagedObjectContextConcurrencyType;
Constants
NSConfinementConcurrencyType
Specifies that the context will use the thread confinement pattern. Available in OS X v10.7 and later. Declared in NSManagedObjectContext.h.
NSPrivateQueueConcurrencyType
Specifies that the context will be associated with a private dispatch queue. Available in OS X v10.7 and later. Declared in NSManagedObjectContext.h.
NSMainQueueConcurrencyType
Specifies that the context will be associated with the main queue. Available in OS X v10.7 and later. Declared in NSManagedObjectContext.h. Discussion See also initWithConcurrencyType: (page 194) and Concurrency with Core Data. Availability Available in OS X v10.7 and later.
217
Declared in
NSManagedObjectContext.h
Notifications
You should typically not register to receive notifications from all managed object contextssee Notifications (page 183).
NSManagedObjectContextObjectsDidChangeNotification
Posted when values of properties of objects contained in a managed object context are changed. The notification is posted during processPendingChanges (page 202), after the changes have been processed, but before it is safe to call save: (page 206) again (if you try, you will generate an infinite loop). The notification object is the managed object context. The userInfo dictionary contains the following keys: NSInsertedObjectsKey, NSUpdatedObjectsKey, and NSDeletedObjectsKey. Note that this notification is posted only when managed objects are changed ; it is not posted when managed objects are added to a context as the result of a fetch. Availability Available in OS X v10.4 and later. Declared in
NSManagedObjectContext.h
NSManagedObjectContextDidSaveNotification
Posted whenever a managed object context completes a save operation. The notification object is the managed object context. The userInfo dictionary contains the following keys: NSInsertedObjectsKey, NSUpdatedObjectsKey, and NSDeletedObjectsKey. You can only use the managed objects in this notification on the same thread on which it was posted. You can pass the notification object to mergeChangesFromContextDidSaveNotification: (page 197) on another thread, however you must not use the managed object in the user info dictionary directly on another thread. For more details, see Concurrency with Core Data. Availability Available in OS X v10.4 and later.
218
Declared in
NSManagedObjectContext.h
NSManagedObjectContextWillSaveNotification
Posted whenever a managed object context is about to perform a save operation. The notification object is the managed object context. There is no userInfo dictionary. Availability Available in OS X v10.6 and later. Declared in
NSManagedObjectContext.h
219
/System/Library/Frameworks/CoreData.framework Available in OS X v10.4 and later. CoreData/NSManagedObjectID.h Core Data Programming Guide
Overview
An NSManagedObjectID object is a compact, universal identifier for a managed object. This forms the basis for uniquing in the Core Data Framework. A managed object ID uniquely identifies the same managed object both between managed object contexts in a single application, and in multiple applications (as in distributed systems). Identifiers contain the information needed to exactly describe an object in a persistent store (like the primary key in the database), although the detailed information is not exposed. The framework completely encapsulates the external information and presents a clean object oriented interface. Object IDs can be transformed into a URI representation which can be archived and recreated later to refer back to a given object (using managedObjectIDForURIRepresentation: (page 283) (NSPersistentStoreCoordinator) and objectWithID: (page 199) (NSManagedObjectContext). For example, the last selected group in an application could be stored in the user defaults through the group objects ID. You can also use object ID URI representations to store weak relationships across persistent stores (where no hard join is possible).
220
Tasks
Information About a Managed Object ID
entity
(page 221) Returns the entity description associated with the receiver. (page 221) Returns a Boolean value that indicates whether the receiver is temporary. (page 222) Returns the persistent store that contains the object whose ID is the receiver. (page 222) Returns a URI that provides an archiveable reference to the object which the receiver represents.
isTemporaryID
persistentStore
URIRepresentation
Instance Methods
entity
Returns the entity description associated with the receiver.
- (NSEntityDescription *)entity
Return Value The entity description object associated with the receiver Availability Available in OS X v10.4 and later. See Also
entity (page 159) (NSManagedObject)
Declared in
NSManagedObjectID.h
isTemporaryID
Returns a Boolean value that indicates whether the receiver is temporary.
- (BOOL)isTemporaryID
221
Return Value YES if the receiver is temporary, otherwise NO. Discussion Most object IDs return NO. New objects inserted into a managed object context are assigned a temporary ID which is replaced with a permanent one once the object gets saved to a persistent store. Availability Available in OS X v10.4 and later. Declared in
NSManagedObjectID.h
persistentStore
Returns the persistent store that contains the object whose ID is the receiver.
- (NSPersistentStore *)persistentStore
Return Value The persistent store that contains the object whose ID is the receiver, or nil if the ID is for a newly-inserted object that has not yet been saved to a persistent store. Availability Available in OS X v10.4 and later. Declared in
NSManagedObjectID.h
URIRepresentation
Returns a URI that provides an archiveable reference to the object which the receiver represents.
- (NSURL *)URIRepresentation
Return Value An NSURL object containing a URI that provides an archiveable reference to the object which the receiver represents. Discussion If the corresponding managed object has not yet been saved, the object ID (and hence URI) is a temporary value that will change when the corresponding managed object is saved.
222
Declared in
NSManagedObjectID.h
223
/System/Library/Frameworks/CoreData.framework Available in OS X v10.4 and later. CoreData/NSManagedObjectModel.h Core Data Programming Guide Core Data Utility Tutorial Core Data Model Versioning and Data Migration Programming Guide
Overview
An NSManagedObjectModel object describes a schemaa collection of entities (data models) that you use in your application. The model contains one or more NSEntityDescription objects representing the entities in the schema. Each NSEntityDescription object has property description objects (instances of subclasses of NSPropertyDescription) that represent the properties (or fields) of the entity in the schema. The Core Data framework uses this description in several ways:
Constraining UI creation in Interface Builder Validating attribute and relationship values at runtime Mapping between your managed objects and a database or file-based schema for object persistence.
224
A managed object model maintains a mapping between each of its entity objects and a corresponding managed object class for use with the persistent storage mechanisms in the Core Data Framework. You can determine the entity for a particular managed object with the entity method. You typically create managed object models using the data modeling tool in Xcode, but it is possible to build a model programmatically if needed.
Configurations
Sometimes a modelparticularly one in a frameworkmay be used in different situations, and you may want to specify different sets of entities to be used in different situations. There might, for example, be certain entities that should only be available if a user has administrative privileges. To support this requirement, a model may have more than one configuration. Each configuration is named, and has an associated set of entities. The sets may overlap. You establish configurations programmatically using setEntities:forConfiguration: (page 238) or using the Xcode design tool, and retrieve the entities for a given configuration name using entitiesForConfiguration: (page 233).
225
Changing Models
Since a model describes the structure of the data in a persistent store, changing any parts of a model that alters the schema renders it incompatible with (and so unable to open) the stores it previously created. If you change your schema, you therefore need to migrate the data in existing stores to new version (see Core Data Model Versioning and Data Migration Programming Guide ). For example, if you add a new entity or a new attribute to an existing entity, you will not be able to open old stores; if you add a validation constraint or set a new default value for an attribute, you will be able to open old stores.
Fast Enumeration
In OS X v10.5 and later and on iOS, NSManagedObjectModel supports the NSFastEnumeration protocol. You can use this to enumerate over a models entities, as illustrated in the following example:
NSManagedObjectModel *aModel = ...; for (NSEntityDescription *entity in aModel) { // entity is each instance of NSEntityDescription in aModel in turn }
Tasks
Initializing a Model
initWithContentsOfURL:
(page 236) Initializes the receiver using the model file at the specified URL. (page 228) Returns a model created by merging all the models found in given bundles.
+ mergedModelFromBundles:
226
+ mergedModelFromBundles:forStoreMetadata:
(page 229) Returns a merged model from a specified array for the version information in provided metadata. (page 230) Creates a single model from an array of existing models. (page 230) Returns, for the version information in given metadata, a model merged from a given array of models.
+ modelByMergingModels:
+ modelByMergingModels:forStoreMetadata:
(page 232) Returns the entities in the receiver. (page 232) Returns the entities of the receiver in a dictionary. (page 238) Sets the entities array of the receiver. (page 231) Returns all the available configuration names of the receiver. (page 233) Returns the entities of the receiver for a specified configuration. (page 238) Associates the specified entities with the receiver using the given configuration name.
entitiesByName
setEntities:
configurations
entitiesForConfiguration:
setEntities:forConfiguration:
(page 235) Returns a dictionary of the receivers fetch request templates. (page 235) Returns the fetch request with a specified name. (page 234) Returns a copy of the fetch request template with the variables substituted by values from the substitutions dictionary. (page 239) Associates the specified fetch request with the receiver using the given name.
fetchRequestTemplateForName:
fetchRequestFromTemplateWithName:substitutionVariables:
setFetchRequestTemplate:forName:
227
Localization
localizationDictionary
(page 237) Returns the localization dictionary of the receiver. (page 240) Sets the localization dictionary of the receiver.
setLocalizationDictionary:
(page 236) Returns a Boolean value that indicates whether a given configuration in the receiver is compatible with given metadata from a persistent store. (page 233) Returns a dictionary of the version hashes for the entities in the receiver. (page 241) Returns the collection of developer-defined version identifiers for the receiver. (page 241) Sets the identifiers for the receiver.
entityVersionHashesByName
versionIdentifiers
setVersionIdentifiers:
Class Methods
mergedModelFromBundles:
Returns a model created by merging all the models found in given bundles.
+ (NSManagedObjectModel *)mergedModelFromBundles:(NSArray *)bundles
Parameters
bundles
An array of instances of NSBundle to search. If you specify nil, then the main bundle is searched. Return Value A model created by merging all the models found in bundles. Availability Available in OS X v10.4 and later.
228
See Also
+ mergedModelFromBundles:forStoreMetadata: + modelByMergingModels:
(page 229)
+ modelByMergingModels:forStoreMetadata: initWithContentsOfURL:
Declared in
NSManagedObjectModel.h
mergedModelFromBundles:forStoreMetadata:
Returns a merged model from a specified array for the version information in provided metadata.
+ (NSManagedObjectModel *)mergedModelFromBundles:(NSArray *)bundles
forStoreMetadata:(NSDictionary *)metadata
Parameters
bundles
An array of bundles.
metadata
A dictionary containing version information from the metadata for a persistent store. Return Value The managed object model used to create the store for the metadata. If a model cannot be created to match the version information specified by metadata, returns nil. Discussion This method is a companion to mergedModelFromBundles: (page 228). Availability Available in OS X v10.5 and later. See Also (page 228) + modelByMergingModels: (page 230)
+ mergedModelFromBundles: + modelByMergingModels:forStoreMetadata: initWithContentsOfURL:
(page 230)
(page 236)
Declared in
NSManagedObjectModel.h
229
modelByMergingModels:
Creates a single model from an array of existing models.
+ (NSManagedObjectModel *)modelByMergingModels:(NSArray *)models
Parameters
models
An array of instances of NSManagedObjectModel. Return Value A single model made by combining the models in models. Discussion You use this method to combine multiple models (typically from different frameworks) into one. Availability Available in OS X v10.4 and later. See Also
+ mergedModelFromBundles:
(page 228)
Declared in
NSManagedObjectModel.h
modelByMergingModels:forStoreMetadata:
Returns, for the version information in given metadata, a model merged from a given array of models.
+ (NSManagedObjectModel *)modelByMergingModels:(NSArray *)models
forStoreMetadata:(NSDictionary *)metadata
Parameters
models
A dictionary containing version information from the metadata for a persistent store.
230
Return Value A merged model from models for the version information in metadata. If a model cannot be created to match the version information in metadata, returns nil. Discussion This is the companion method to mergedModelFromBundles:forStoreMetadata: (page 229). Availability Available in OS X v10.5 and later. See Also
+ mergedModelFromBundles: + modelByMergingModels:
+ mergedModelFromBundles:forStoreMetadata:
Instance Methods
configurations
Returns all the available configuration names of the receiver.
- (NSArray *)configurations
Return Value An array containing the available configuration names of the receiver. Availability Available in OS X v10.4 and later. See Also
entitiesForConfiguration: setEntities:forConfiguration:
Declared in
NSManagedObjectModel.h
231
entities
Returns the entities in the receiver.
- (NSArray *)entities
Return Value An array containing the entities in the receiver. Discussion Entities are instances of NSEntityDescription. Availability Available in OS X v10.4 and later. See Also
entitiesByName setEntities:
entitiesForConfiguration:
(page 238)
setEntities:forConfiguration:
Declared in
NSManagedObjectModel.h
entitiesByName
Returns the entities of the receiver in a dictionary.
- (NSDictionary *)entitiesByName
Return Value The entities of the receiver in a dictionary, where the keys in the dictionary are the names of the corresponding entities. Availability Available in OS X v10.4 and later. See Also
entities
(page 232) (page 233) (page 238) (page 44) (NSEntityDescription) (page 238)
entitiesForConfiguration: setEntities:
setEntities:forConfiguration:
+ entityForName:inManagedObjectContext:
232
Declared in
NSManagedObjectModel.h
entitiesForConfiguration:
Returns the entities of the receiver for a specified configuration.
- (NSArray *)entitiesForConfiguration:(NSString *)configuration
Parameters
configuration
The name of a configuration in the receiver. Return Value An array containing the entities of the receiver for the configuration specified by configuration. Availability Available in OS X v10.4 and later. See Also (page 232) entitiesByName (page 232) setEntities: (page 238)
entities setEntities:forConfiguration:
(page 238)
Declared in
NSManagedObjectModel.h
entityVersionHashesByName
Returns a dictionary of the version hashes for the entities in the receiver.
- (NSDictionary *)entityVersionHashesByName
Return Value A dictionary of the version hashes for the entities in the receiver, keyed by entity name. Discussion The dictionary of version hash information is used by Core Data to determine schema compatibility.
233
(page 236)
Declared in
NSManagedObjectModel.h
fetchRequestFromTemplateWithName:substitutionVariables:
Returns a copy of the fetch request template with the variables substituted by values from the substitutions dictionary.
- (NSFetchRequest *)fetchRequestFromTemplateWithName:(NSString *)name
substitutionVariables:(NSDictionary *)variables
Parameters
name
A dictionary containing key-value pairs where the keys are the names of variables specified in the template; the corresponding values are substituted before the fetch request is returned. The dictionary must provide values for all the variables in the template. Return Value A copy of the fetch request template with the variables substituted by values from variables. Discussion The variables dictionary must provide values for all the variables. If you want to test for a nil value, use [NSNull null]. This method provides the usual way to bind an abstractly defined fetch request template to a concrete fetch. For more details on using this method, see Creating Predicates. Availability Available in OS X v10.4 and later. See Also (page 235) fetchRequestTemplateForName: (page 235) setFetchRequestTemplate:forName: (page 239)
fetchRequestTemplatesByName
234
Declared in
NSManagedObjectModel.h
fetchRequestTemplateForName:
Returns the fetch request with a specified name.
- (NSFetchRequest *)fetchRequestTemplateForName:(NSString *)name
Parameters
name
A string containing the name of a fetch request template. Return Value The fetch request named name. Discussion If the template contains substitution variables, you should instead use
fetchRequestFromTemplateWithName:substitutionVariables: (page 234) to create a new fetch request.
fetchRequestFromTemplateWithName:substitutionVariables: setFetchRequestTemplate:forName:
Declared in
NSManagedObjectModel.h
fetchRequestTemplatesByName
Returns a dictionary of the receivers fetch request templates.
- (NSDictionary *)fetchRequestTemplatesByName
Return Value A dictionary of the receivers fetch request templates, keyed by name. Discussion If the template contains a predicate with substitution variables, you should instead use fetchRequestFromTemplateWithName:substitutionVariables: (page 234) to create a new fetch request.
235
fetchRequestFromTemplateWithName:substitutionVariables:
Declared in
NSManagedObjectModel.h
initWithContentsOfURL:
Initializes the receiver using the model file at the specified URL.
- (id)initWithContentsOfURL:(NSURL *)url
Parameters
url
An URL object specifying the location of a model file. Return Value A managed object model initialized using the file at url. Availability Available in OS X v10.4 and later. See Also
+ mergedModelFromBundles: + modelByMergingModels:
+ mergedModelFromBundles:forStoreMetadata:
+ modelByMergingModels:forStoreMetadata:
Declared in
NSManagedObjectModel.h
isConfiguration:compatibleWithStoreMetadata:
Returns a Boolean value that indicates whether a given configuration in the receiver is compatible with given metadata from a persistent store.
- (BOOL)isConfiguration:(NSString *)configuration
compatibleWithStoreMetadata:(NSDictionary *)metadata
236
Parameters
configuration
Metadata for a persistent store. Return Value YES if the configuration in the receiver specified by configuration is compatible with the store metadata given by metadata, otherwise NO. Discussion This method compares the version information in the store metadata with the entity versions of a given configuration. For information on specific differences, use entityVersionHashesByName (page 233) and perform an entity-by-entity comparison. Availability Available in OS X v10.5 and later. See Also
entityVersionHashesByName
(page 233)
Declared in
NSManagedObjectModel.h
localizationDictionary
Returns the localization dictionary of the receiver.
- (NSDictionary *)localizationDictionary
Return Value The localization dictionary of the receiver. Discussion The key-value pattern is described in setLocalizationDictionary: (page 240). Special Considerations On OS X v10.4, localizationDictionary may return nil until Core Data lazily loads the dictionary for its own purposes (for example, reporting a localized error). Availability Available in OS X v10.4 and later.
237
See Also
setLocalizationDictionary:
(page 240)
Declared in
NSManagedObjectModel.h
setEntities:
Sets the entities array of the receiver.
- (void)setEntities:(NSArray *)entities
Parameters
entities
An array of instances of NSEntityDescription. Special Considerations This method raises an exception if the receiver has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also (page 232) entitiesByName (page 232)
entities
Declared in
NSManagedObjectModel.h
setEntities:forConfiguration:
Associates the specified entities with the receiver using the given configuration name.
- (void)setEntities:(NSArray *)entities forConfiguration:(NSString *)configuration
Parameters
entities
238
configuration
A name for the configuration. Special Considerations This method raises an exception if the receiver has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also (page 232) entitiesByName (page 232)
entities entitiesForConfiguration: setEntities:
(page 233)
(page 238)
Declared in
NSManagedObjectModel.h
setFetchRequestTemplate:forName:
Associates the specified fetch request with the receiver using the given name.
- (void)setFetchRequestTemplate:(NSFetchRequest *)fetchRequest forName:(NSString
*)name
Parameters
fetchRequest
A string that specifies the name of the fetch request template. Discussion For more details on using this method, see Creating Predicates. Special Considerations This method raises an exception if the receiver has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also (page 235) fetchRequestTemplateForName: (page 235)
fetchRequestTemplatesByName
239
fetchRequestFromTemplateWithName:substitutionVariables:
(page 234)
Declared in
NSManagedObjectModel.h
setLocalizationDictionary:
Sets the localization dictionary of the receiver.
- (void)setLocalizationDictionary:(NSDictionary *)localizationDictionary
Parameters
localizationDictionary
A dictionary containing localized string values for entities, properties, and error strings related to the model. The key and value pattern is described in Table 16-1 (page 240). Discussion Table 16-1 (page 240) describes the key and value pattern for the localization dictionary.
Table 16-1 Key Key and value pattern for the localization dictionary. Value Note
(1) For properties in different entities with the same non-localized name but which should have different localized names. Availability Available in OS X v10.4 and later. See Also
localizationDictionary
(page 237)
240
Declared in
NSManagedObjectModel.h
setVersionIdentifiers:
Sets the identifiers for the receiver.
- (void)setVersionIdentifiers:(NSSet *)identifiers
Parameters
identifiers
An array of identifiers for the receiver. Availability Available in OS X v10.5 and later. See Also
versionIdentifiers
(page 241)
Declared in
NSManagedObjectModel.h
versionIdentifiers
Returns the collection of developer-defined version identifiers for the receiver.
- (NSSet *)versionIdentifiers
Return Value The collection of developer-defined version identifiers for the receiver. Merged models return the combined collection of identifiers. Discussion The Core Data framework does not give models a default identifier, nor does it depend this value at runtime. For models created in Xcode, you set this value in the model inspector. This value is meant to be used as a debugging hint to help you determine the models that were combined to create a merged model. Availability Available in OS X v10.5 and later.
241
See Also
setVersionIdentifiers:
(page 241)
Declared in
NSManagedObjectModel.h
242
NSObject NSObject (NSObject) /System/Library/Frameworks/CoreData.framework Available in OS X v10.5 and later. CoreData/NSMappingModel.h Core Data Model Versioning and Data Migration Programming Guide
Overview
Instances of NSMappingModel specify how to map from a source to a destination managed object model.
Tasks
Creating a Mapping
+ mappingModelFromBundles:forSourceModel:destinationModel:
(page 245) Returns the mapping model to translate data from the source to the destination model. (page 244) Returns a newly-created mapping model to migrate data from the source to the destination model. (page 246) Returns a mapping model initialized from a given URL.
+ inferredMappingModelForSourceModel:destinationModel:error:
initWithContentsOfURL:
(page 245) Returns the collection of entity mappings for the receiver.
243
setEntityMappings:
(page 247) Sets the collection of entity mappings for the receiver (page 246) Returns a dictionary of the entity mappings for the receiver.
entityMappingsByName
Class Methods
inferredMappingModelForSourceModel:destinationModel:error:
Returns a newly-created mapping model to migrate data from the source to the destination model.
+ (NSMappingModel *)inferredMappingModelForSourceModel:(NSManagedObjectModel *)source
Parameters
source
If a problem occurs, on return contains an NSInferredMappingModelError error that describes the problem. The error user s info will contain additional details about why inferring the mapping model failed (check for the following keys: reason, entity, property. Return Value A newly-created mapping model to migrate data from the source to the destination model. If the mapping model can not be created, returns nil. Discussion A model will be created only if all changes are simple enough to be able to reasonably infer a mapping (for example, removing or renaming an attribute, adding an optional attribute or relationship, or adding renaming or deleting an entity). Element IDs are used to track renamed properties and entities. Availability Available in OS X v10.6 and later. Declared in
NSMappingModel.h
244
mappingModelFromBundles:forSourceModel:destinationModel:
Returns the mapping model to translate data from the source to the destination model.
+ (NSMappingModel *)mappingModelFromBundles:(NSArray *)bundles
Parameters
bundles
The managed object model for the destination store. Return Value Returns the mapping model to translate data from sourceModel to destinationModel. If a suitable mapping model cannot be found, returns nil. Discussion This method is a companion to the mergedModelFromBundles: (page 228) and mergedModelFromBundles:forStoreMetadata: (page 229) methods. In this case, the framework uses the version information from the models to locate the appropriate mapping model in the available bundles. Availability Available in OS X v10.5 and later. See Also
initWithContentsOfURL:
(page 246)
Declared in
NSMappingModel.h
Instance Methods
entityMappings
Returns the collection of entity mappings for the receiver.
- (NSArray *)entityMappings
245
Return Value The collection of entity mappings for the receiver. Special Considerations The order of the mappings in the array specifies the order in which they will be processed during migration. Availability Available in OS X v10.5 and later. See Also (page 247) entityMappingsByName (page 246)
setEntityMappings:
Declared in
NSMappingModel.h
entityMappingsByName
Returns a dictionary of the entity mappings for the receiver.
- (NSDictionary *)entityMappingsByName
Return Value A dictionary of the entity mappings for the receiver, keyed by their respective name. Discussion You can use this method to quickly access to mapping by name, rather than iterating the ordered array returned by entityMappings (page 245). Availability Available in OS X v10.5 and later. See Also
entityMappings
(page 245)
Declared in
NSMappingModel.h
initWithContentsOfURL:
Returns a mapping model initialized from a given URL.
246
- (id)initWithContentsOfURL:(NSURL *)url
Parameters
url
The location of an archived mapping model. Return Value A mapping model initialized from url. Availability Available in OS X v10.5 and later. See Also
+ mappingModelFromBundles:forSourceModel:destinationModel:
(page 245)
Declared in
NSMappingModel.h
setEntityMappings:
Sets the collection of entity mappings for the receiver
- (void)setEntityMappings:(NSArray *)mappings
Parameters
mappings
The collection of entity mappings for the receiver. Special Considerations The order of the mappings specifies the order in which they will be processed during migration. Availability Available in OS X v10.5 and later. See Also
entityMappings
(page 245)
Declared in
NSMappingModel.h
247
NSObject NSObject (NSObject) /System/Library/Frameworks/CoreData.framework Available in OS X v10.7 and later. NSMergePolicy.h Core Data Model Versioning and Data Migration Programming Guide
Overview
A merge conflict encapsulates conflicts that occur when attempting to save changes in a managed object context. There are two situations in which a conflict may occur:
1.
Between the managed object context and its in-memory cached state at the persistent store coordinator layer. In this case, the merge conflict has a source object and a cached snapshot but no persisted snapshot.
2.
Between the cached state at the persistent store coordinator and the external store (file, database, etc.). In this case, the merge conflict has a cached snapshot and a persisted snapshot. The source object is also provided as a convenience, but it is not directly involved in the conflict.
Snapshot dictionaries include values for all attributes and to-one relationships, but not to-many relationships. Relationship values are NSManagedObjectID references. To-many relationships must be pulled from the persistent store as needed.
248
Tasks
Initializing a Merge Conflict
initWithSource:newVersion:oldVersion:cachedSnapshot:persistedSnapshot:
(page 251)
property
property
property
A dictionary containing the values of the source object held in the persistent store coordinator layer. (read-only)
persistedSnapshot (page 250)
property
A dictionary containing the values of the source object held in the persistent store. (read-only)
newVersionNumber (page 249)
property
property
Properties
cachedSnapshot
A dictionary containing the values of the source object held in the persistent store coordinator layer. (read-only)
@property(readonly, retain) NSDictionary *cachedSnapshot
newVersionNumber
The new version number for the change. (read-only)
249
Discussion A new version number of 0 means the object was deleted and the corresponding snapshot is nil. Availability Available in OS X v10.7 and later. Declared in
NSMergePolicy.h
objectSnapshot
A dictionary containing the values of the source object. (read-only)
@property(readonly, retain) NSDictionary *objectSnapshot
oldVersionNumber
The old version number for the change. (read-only)
@property(readonly) NSUInteger oldVersionNumber
persistedSnapshot
A dictionary containing the values of the source object held in the persistent store. (read-only)
250
sourceObject
The source object for the conflict. (read-only)
@property(readonly, retain) NSManagedObject *sourceObject
Instance Methods
initWithSource:newVersion:oldVersion:cachedSnapshot:persistedSnapshot:
Initializes a merge conflict.
- (id)initWithSource:(NSManagedObject *)srcObject newVersion:(NSUInteger)newvers
Parameters
srcObject
The new version number for the change. A value of 0 means the object was deleted and the corresponding snapshot is nil.
oldvers
A dictionary containing the values of srcObject held in the persistent store coordinator layer.
251
persnap
A dictionary containing the values of srcObject held in the persistent store. Return Value A merge conflict object initialized with the given parameters. Availability Available in OS X v10.7 and later. Declared in
NSMergePolicy.h
252
NSObject NSObject (NSObject) /System/Library/Frameworks/CoreData.framework Available in OS X v10.7 and later. NSMergePolicy.h Core Data Model Versioning and Data Migration Programming Guide
Overview
You use a merge policy object to resolve conflicts between the persistent store and in-memory versions of managed objects. A conflict is a mismatch between state held at two different layers in the Core Data stack. A conflict can arise when you save a managed object context when you have stale data at some layer. There are two places in which a conflict may occur:
Between the managed object context and its in-memory cached state at the persistent store coordinator layer. Between the cached state at the persistent store coordinator and the external store (file, database, etc.).
Tasks
Using a Merge Policy
initWithMergeType:
(page 254) Returns a merge policy initialized with a given policy type.
253
resolveConflicts:error:
Properties
mergeType
The merge type.
@property (readonly) NSMergePolicyType mergeType
Instance Methods
initWithMergeType:
Returns a merge policy initialized with a given policy type.
- (id)initWithMergeType:(NSMergePolicyType)ty
Parameters
ty
A merge policy type. Return Value A merge policy initialized with a given policy type. Discussion If you override this method in a subclass, you should invoke the superclasss implementation with the merge policy that is closest to the behavior you want.
254
This will make it easier to use the superclasss implementation of resolveConflicts:error: (page 255) and then customize the results. Due to the complexity of merging to-many relationships, this class is designed with the expectation that you call super as the base implementation.
resolveConflicts:error:
Resolves the conflicts in a given list.
- (BOOL)resolveConflicts:(NSArray*)list
error:(NSError **)error
Parameters
list
If an error occurs, upon return contains an NSError object that describes the problem. Return Value YES if the conflicts were resolved successfully, otherwise NO. Discussion If you override this method in a subclass, you should typically invoke the superclasss implementation in addition to performing your own operations. Availability Available in OS X v10.7 and later. Declared in
NSMergePolicy.h
255
Constants
Merge Policies
Merge policy singleton objects that define standard ways to handle conflicts during a save operation.
id id id id id
Constants
NSErrorMergePolicy
This policy causes a save to fail if there are any merge conflicts. This is the default policy for all managed object contexts. In the case of failure, the save method returns with an error with a userInfo dictionary that contains the object IDs of the objects that had conflicts (NSInsertedObjectsKey (page 215), NSUpdatedObjectsKey (page 215)). Available in OS X v10.4 and later. Declared in NSManagedObjectContext.h.
NSMergeByPropertyStoreTrumpMergePolicy
This policy merges conflicts between the persistent stores version of the object and the current in-memory version, giving priority to external changes. The merge occurs by individual property. For properties that have been changed in both the external source and in memory, the external changes trump the in-memory ones. Available in OS X v10.4 and later. Declared in NSManagedObjectContext.h.
NSMergeByPropertyObjectTrumpMergePolicy
This policy merges conflicts between the persistent stores version of the object and the current in-memory version, giving priority to in-memory changes. The merge occurs by individual property. For properties that have been changed in both the external source and in memory, the in-memory changes trump the external ones. Available in OS X v10.4 and later. Declared in NSManagedObjectContext.h.
256
NSOverwriteMergePolicy
This policy overwrites state in the persistent store for the changed objects in conflict. Changed objects current state is forced upon the persistent store. Available in OS X v10.4 and later. Declared in NSManagedObjectContext.h.
NSRollbackMergePolicy
This policy discards in-memory state changes for objects in conflict. The persistent stores version of the objects state is used. Available in OS X v10.4 and later. Declared in NSManagedObjectContext.h. Discussion The default policy is the NSErrorMergePolicy. It is the only policy that requires action to correct any conflicts; the other policies make a save go through silently by making changes following their rules.
NSMergePolicyType
Constants to define merge policy types.
= = = = =
Constants
NSErrorMergePolicyType
Specifies a policy that causes a save to fail if there are any merge conflicts. Available in OS X v10.7 and later. Declared in NSMergePolicy.h.
NSMergeByPropertyStoreTrumpMergePolicyType
Specifies a policy that merges conflicts between the persistent stores version of the object and the current in-memory version, giving priority to external changes. Available in OS X v10.7 and later. Declared in NSMergePolicy.h.
257
NSMergeByPropertyObjectTrumpMergePolicyType
Specifies a policy that merges conflicts between the persistent stores version of the object and the current in-memory version, giving priority to in-memory changes. Available in OS X v10.7 and later. Declared in NSMergePolicy.h.
NSOverwriteMergePolicyType
Specifies a policy that overwrites state in the persistent store for the changed objects in conflict. Available in OS X v10.7 and later. Declared in NSMergePolicy.h.
NSRollbackMergePolicyType
Specifies a policy that discards in-memory state changes for objects in conflict. Available in OS X v10.7 and later. Declared in NSMergePolicy.h.
258
NSObject NSObject (NSObject) /System/Library/Frameworks/CoreData.framework Available in OS X v10.5 and later. NSPersistentStore.h Core Data Programming Guide Atomic Store Programming Topics Incremental Store Programming Guide
Overview
This class is the abstract base class for all Core Data persistent stores. Core Data provides four store typesSQLite, Binary, XML, and In-Memory (the XML store is not available on iOS); these are described in Persistent Store Features. Core Data also provides subclasses of NSPersistentStore that you can use to define your own store types: NSAtomicStore and NSIncrementalStore. The Binary and XML stores are examples of atomic stores that inherit functionality from NSAtomicStore.
Subclassing Notes
You should not subclass NSPersistentStore directly. Core Data only supports subclassing of NSAtomicStore and NSIncrementalStore. The designated initializer is initWithPersistentStoreCoordinator:configurationName:URL:options: (page 265). When you implement the initializer, you must ensure you load metadata during initialization and set it using setMetadata: (page 268). You must override these methods:
259
type (page 270) metadata (page 267) metadataForPersistentStoreWithURL:error: (page 261) setMetadata:forPersistentStoreWithURL:error: (page 263)
Tasks
Initializing a Persistent Store
initWithPersistentStoreCoordinator:configurationName:URL:options:
(page 265)
(page 270) Returns the type string of the receiver. (page 267) Returns the persistent store coordinator which loaded the receiver. (page 263) Returns the name of the managed object model configuration used to create the receiver. (page 267) Returns the options with which the receiver was created. (page 270) Returns the URL for the receiver. (page 269) Sets the URL for the receiver. (page 264) Returns the unique identifier for the receiver. (page 268) Sets the unique identifier for the receiver. (page 266) Returns a Boolean value that indicates whether the receiver is read-only.
persistentStoreCoordinator
configurationName
options
URL
setURL:
identifier
setIdentifier:
isReadOnly
260
setReadOnly:
Managing Metadata
+ metadataForPersistentStoreWithURL:error:
(page 261) Returns the metadata from the persistent store at the given URL. (page 263) Sets the metadata for the store at a given URL.
+ setMetadata:forPersistentStoreWithURL:error:
metadata
(page 267) Returns the metadata for the receiver. (page 266) Instructs the receiver to load its metadata. (page 268) Sets the metadata for the receiver.
loadMetadata:
setMetadata:
(page 264) Invoked after the receiver has been added to the persistent store coordinator. (page 270) Invoked before the receiver is removed from the persistent store coordinator.
willRemoveFromPersistentStoreCoordinator:
Supporting Migration
+ migrationManagerClass
(page 262)
Class Methods
metadataForPersistentStoreWithURL:error:
Returns the metadata from the persistent store at the given URL.
261
**)error
Parameters
url
If an error occurs, upon return contains an NSError object that describes the problem. Return Value The metadata from the persistent store at url. Returns nil if there is an error. Special Considerations Subclasses must override this method. Availability Available in OS X v10.5 and later. Declared in
NSPersistentStore.h
migrationManagerClass
Returns the NSMigrationManager class for this store class.
+ (Class)migrationManagerClass
Return Value The NSMigrationManager class for this store class Discussion In a subclass of NSPersistentStore, you can override this to provide a custom migration manager subclass (for example, to take advantage of store-specific functionality to improve migration performance). Availability Available in OS X v10.6 and later. Declared in
NSPersistentStore.h
262
setMetadata:forPersistentStoreWithURL:error:
Sets the metadata for the store at a given URL.
+ (BOOL)setMetadata:(NSDictionary *)metadata forPersistentStoreWithURL:(NSURL *)url
error:(NSError **)error
Parameters
metadata
If an error occurs, upon return contains an NSError object that describes the problem. Return Value YES if the metadata was written correctly, otherwise NO. Special Considerations Subclasses must override this method to set metadata appropriately. Availability Available in OS X v10.5 and later. Declared in
NSPersistentStore.h
Instance Methods
configurationName
Returns the name of the managed object model configuration used to create the receiver.
- (NSString *)configurationName
Return Value The name of the managed object model configuration used to create the receiver. Availability Available in OS X v10.5 and later.
263
Declared in
NSPersistentStore.h
didAddToPersistentStoreCoordinator:
Invoked after the receiver has been added to the persistent store coordinator.
- (void)didAddToPersistentStoreCoordinator:(NSPersistentStoreCoordinator *)coordinator
Parameters
coordinator
The persistent store coordinator to which the receiver was added. Discussion The default implementation does nothing. You can override this method in a subclass in order to perform any kind of setup necessary before the load method is invoked. Availability Available in OS X v10.5 and later. Declared in
NSPersistentStore.h
identifier
Returns the unique identifier for the receiver.
- (NSString *)identifier
Return Value The unique identifier for the receiver. Discussion The identifier is used as part of the managed object IDs for each object in the store. Special Considerations NSPersistentStore provides a default implementation to provide a globally unique identifier for the store instance. Availability Available in OS X v10.5 and later.
264
Declared in
NSPersistentStore.h
initWithPersistentStoreCoordinator:configurationName:URL:options:
Returns a store initialized with the given arguments.
- (id)initWithPersistentStoreCoordinator:(NSPersistentStoreCoordinator *)root
Parameters
coordinator
The name of the managed object model configuration to use. Pass nil if you do not want to specify a configuration.
url
A dictionary containing configuration options. See NSPersistentStoreCoordinator for a list of key names for options in this dictionary. Return Value A new store object, associated with coordinator, that represents a persistent store at url using the options in options andif it is not nilthe managed object model configuration configurationName. Discussion You must ensure that you load metadata during initialization and set it using setMetadata: (page 268). Special Considerations This is the designated initializer for persistent stores. Availability Available in OS X v10.5 and later. See Also
setMetadata:
(page 268)
265
Declared in
NSPersistentStore.h
isReadOnly
Returns a Boolean value that indicates whether the receiver is read-only.
- (BOOL)isReadOnly
Return Value YES if the receiver is read-only, otherwise NO. Availability Available in OS X v10.5 and later. Declared in
NSPersistentStore.h
loadMetadata:
Instructs the receiver to load its metadata.
- (BOOL)loadMetadata:(NSError **)error
Parameters
error
If an error occurs, upon return contains an NSError object that describes the problem. Return Value YES if the metadata was loaded correctly, otherwise NO. Special Considerations There is no way to return an error if the store is invalid. Availability Available in OS X v10.6 and later. Declared in
NSPersistentStore.h
266
metadata
Returns the metadata for the receiver.
- (NSDictionary *)metadata
Return Value The metadata for the receiver. The dictionary must include the store type (NSStoreTypeKey (page 292)) and UUID (NSStoreUUIDKey (page 292)). Special Considerations Subclasses must override this method to provide storage and persistence for the store metadata. Availability Available in OS X v10.5 and later. Declared in
NSPersistentStore.h
options
Returns the options with which the receiver was created.
- (NSDictionary *)options
Return Value The options with which the receiver was created. Discussion See NSPersistentStoreCoordinator for a list of key names for options in this dictionary. Availability Available in OS X v10.5 and later. Declared in
NSPersistentStore.h
persistentStoreCoordinator
Returns the persistent store coordinator which loaded the receiver.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
267
Return Value The persistent store coordinator which loaded the receiver. Availability Available in OS X v10.5 and later. Declared in
NSPersistentStore.h
setIdentifier:
Sets the unique identifier for the receiver.
- (void)setIdentifier:(NSString *)identifier
Parameters
identifier
The unique identifier for the receiver. Availability Available in OS X v10.5 and later. See Also (page 264) metadata (page 267)
identifier
Declared in
NSPersistentStore.h
setMetadata:
Sets the metadata for the receiver.
- (void)setMetadata:(NSDictionary *)storeMetadata
Parameters
storeMetadata
The metadata for the receiver. Availability Available in OS X v10.5 and later.
268
Declared in
NSPersistentStore.h
setReadOnly:
Sets whether the receiver is read-only.
- (void)setReadOnly:(BOOL)flag
Parameters
flag YES if the receiver is read-only, otherwise NO.
setURL:
Sets the URL for the receiver.
- (void)setURL:(NSURL *)url
Parameters
url
The URL for the receiver. Discussion To alter the location of a store, send the persistent store coordinator a setURL:forPersistentStore: (page 288) message. Availability Available in OS X v10.5 and later. See Also URL (page 270) Declared in
NSPersistentStore.h
269
type
Returns the type string of the receiver.
- (NSString *)type
Return Value The type string of the receiver. Discussion This string is used when specifying the type of store to add to a persistent store coordinator. Special Considerations Subclasses must override this method to provide a unique type. Availability Available in OS X v10.5 and later. Declared in
NSPersistentStore.h
URL
Returns the URL for the receiver.
- (NSURL *)URL
Return Value The URL for the receiver. Availability Available in OS X v10.5 and later. See Also
setURL:
(page 269)
Declared in
NSPersistentStore.h
willRemoveFromPersistentStoreCoordinator:
Invoked before the receiver is removed from the persistent store coordinator.
270
- (void)willRemoveFromPersistentStoreCoordinator:(NSPersistentStoreCoordinator
*)coordinator
Parameters
coordinator
The persistent store coordinator from which the receiver was removed. Discussion The default implementation does nothing. You can override this method in a subclass in order to perform any clean-up before the store is removed from the coordinator (and deallocated). Availability Available in OS X v10.5 and later. Declared in
NSPersistentStore.h
271
/System/Library/Frameworks/CoreData.framework Available in OS X v10.4 and later. CoreData/NSPersistentStoreCoordinator.h Core Data Programming Guide Core Data Spotlight Integration Programming Guide
Overview
Instances of NSPersistentStoreCoordinator associate persistent stores (by type) with a model (or more accurately, a configuration of a model) and serve to mediate between the persistent store or stores and the managed object context or contexts. Instances of NSManagedObjectContext use a coordinator to save object graphs to persistent storage and to retrieve model information. A context without a coordinator is not fully functional as it cannot access a model except through a coordinator. The coordinator is designed to present a faade to the managed object contexts such that a group of persistent stores appears as an aggregate store. A managed object context can then create an object graph based on the union of all the data stores the coordinator covers. Coordinators do the opposite of providing for concurrency y the serialize operations. If you want to use multiple threads for different write operations you use multiple coordinators. Note that if multiple threads work directly with a coordinator, they need to lock and unlock it explicitly. Each coordinator (and thus container) may use different copies, and hence different versions, of a managed object model. This allows you to cleanly deal with file versioning.
272
The coordinator gives access to its underlying object stores. You can retrieve an object store when you first add one (using addPersistentStoreWithType:configuration:URL:options:error: (page 279)), or by using persistentStoreForURL: (page 286) or persistentStores (page 287). This allows you to to determine, for example, whether a store has already been added, or whether two objects come from the same store.
You move a store from one location to another, or change the type of a store, using migratePersistentStore:toURL:options:withType:error: (page 285). You can set metadata for a given store using the persistent store coordinator (setMetadata:forPersistentStore: (page 288)).
For more details about these tasks, see Persistent Store Features in Core Data Programming Guide .
Tasks
Registered Store Types
+ registeredStoreTypes
(page 278) Returns a dictionary of the registered store types. (page 278) Registers a given NSPersistentStore subclass for a given store type string.
+ registerStoreClass:forStoreType:
Initializing a Coordinator
initWithManagedObjectModel:
(page 282) Initializes the receiver with a managed object model. (page 284) Returns the receivers managed object model.
managedObjectModel
(page 279) Adds a new persistent store of a specified type at a given location, and returns the new store. (page 288) Sets the URL for a given persistent store.
setURL:forPersistentStore:
273
removePersistentStore:error:
(page 287) Removes a given persistent store. (page 285) Moves a persistent store to a new location, changing the storage type if necessary. (page 287) Returns an array of persistent stores associated with the receiver. (page 286) Returns the persistent store for the specified URL. (page 290) Returns the URL for a given persistent store.
migratePersistentStore:toURL:options:withType:error:
persistentStores
persistentStoreForURL:
URLForPersistentStore:
(page 281) Sends a request to all the persistent stores associated with the receiver.
Locking
lock
(page 283) Attempts to acquire a lock. (page 289) Attempts to acquire a lock. (page 290) Relinquishes a previously acquired lock.
tryLock
unlock
(page 284) Returns a dictionary that contains the metadata currently stored or to-be-stored in a given persistent store. (page 288) Sets the metadata stored in the persistent store during the next save operation executed on it to metadata.
setMetadata:forPersistentStore:
274
+ setMetadata:forPersistentStoreOfType:URL:error:
(page 279)
(page 276) Returns a dictionary containing the metadata stored in the persistent store at a given URL. (page 277) Deprecated in OS X v10.5 Returns a dictionary that contains the metadata stored in the persistent store at the specified location. (Deprecated. Use metadataForPersistentStoreOfType:URL:error: (page 276) instead.)
+ metadataForPersistentStoreWithURL:error:
(page 275) Returns a dictionary containing the parsed elements derived from the Spotlight external record file specified by the given URL.
importStoreWithIdentifier:fromExternalRecordsDirectory:toURL:options:withType:error: (page
281) Creates and populates a store with the external records found at a given URL.
(page 283) Returns an object ID for the specified URI representation of an object ID if a matching store is available, or nil if a matching store cannot be found.
Class Methods
elementsDerivedFromExternalRecordURL:
Returns a dictionary containing the parsed elements derived from the Spotlight external record file specified by the given URL.
+ (NSDictionary *)elementsDerivedFromExternalRecordURL:(NSURL *)fileURL
Parameters
fileURL
275
Return Value A dictionary containing the parsed elements derived from the Spotlight support file specified by fileURL. Discussion Dictionary keys and the corresponding values are described in Spotlight External Record Elements (page 297). Availability Available in OS X v10.6 and later. Declared in
NSPersistentStoreCoordinator.h
metadataForPersistentStoreOfType:URL:error:
Returns a dictionary containing the metadata stored in the persistent store at a given URL.
+ (NSDictionary *)metadataForPersistentStoreOfType:(NSString *)storeType URL:(NSURL
Parameters
storeType
The type of the store at url. If this value is nil, Core Data determines which store class should be used to get or set the store file's metadata by inspecting the file contents.
url
If no store is found at url or if there is a problem accessing its contents, upon return contains an NSError object that describes the problem. Return Value A dictionary containing the metadata stored in the persistent store at url, or nil if the store cannot be opened or if there is a problem accessing its contents. The keys guaranteed to be in this dictionary are NSStoreTypeKey (page 292) and NSStoreUUIDKey (page 292). Discussion You can use this method to retrieve the metadata from a store without the overhead of creating a Core Data stack. Availability Available in OS X v10.5 and later.
276
See Also
+ setMetadata:forPersistentStoreOfType:URL:error:
(page 279)
Declared in
NSPersistentStoreCoordinator.h
metadataForPersistentStoreWithURL:error:
Returns a dictionary that contains the metadata stored in the persistent store at the specified location. (Deprecated in OS X v10.5. Use metadataForPersistentStoreOfType:URL:error: (page 276) instead.)
+ (NSDictionary *)metadataForPersistentStoreWithURL:(NSURL *)url error:(NSError
**)error
Parameters
url
If no store is found at url or if there is a problem accessing its contents, upon return contains an instance of NSError that describes the problem. Return Value A dictionary containing the metadata for the persistent store at url. If no store is found, or there is a problem accessing its contents, returns nil. The keys guaranteed to be in this dictionary are NSStoreTypeKey and NSStoreUUIDKey. Discussion This method allows you to access the metadata in a persistent store without initializing a Core Data stack. Availability Available in OS X v10.4 and later. Deprecated in OS X v10.5. See Also (page 284) setMetadata:forPersistentStore: (page 288)
metadataForPersistentStore:
277
Declared in
NSPersistentStoreCoordinator.h
registeredStoreTypes
Returns a dictionary of the registered store types.
+ (NSDictionary *)registeredStoreTypes
Return Value A dictionary of the registered store typesthe keys are the store type strings, and the values are the NSPersistentStore subclasses. Availability Available in OS X v10.5 and later. Declared in
NSPersistentStoreCoordinator.h
registerStoreClass:forStoreType:
Registers a given NSPersistentStore subclass for a given store type string.
+ (void)registerStoreClass:(Class)storeClass forStoreType:(NSString *)storeType
Parameters
storeClass
A unique string that identifies a store type. Discussion You must invoke this method before a custom subclass of NSPersistentStore can be loaded into a persistent store coordinator. You can pass nil for storeClass to unregister the store type. Availability Available in OS X v10.5 and later. Declared in
NSPersistentStoreCoordinator.h
278
setMetadata:forPersistentStoreOfType:URL:error:
Sets the metadata for a given store.
+ (BOOL)setMetadata:(NSDictionary *)metadata forPersistentStoreOfType:(NSString
Parameters
metadata
The type of the store at url. If this value is nil, Core Data will determine which store class should be used to get or set the store file's metadata by inspecting the file contents.
url
If no store is found at url or if there is a problem setting its metadata, upon return contains an NSError object that describes the problem. Return Value YES if the metadata was set correctly, otherwise NO. Discussion You can use this method to set the metadata for a store without the overhead of creating a Core Data stack. Availability Available in OS X v10.5 and later. See Also
+ metadataForPersistentStoreOfType:URL:error:
(page 276)
Declared in
NSPersistentStoreCoordinator.h
Instance Methods
addPersistentStoreWithType:configuration:URL:options:error:
Adds a new persistent store of a specified type at a given location, and returns the new store.
279
Parameters
storeType
A string constant (such as NSSQLiteStoreType) that specifies the store typesee Store Types (page 291) for possible values.
configuration
The name of a configuration in the receiver's managed object model that will be used by the new store. The configuration can be nil, in which case no other configurations are allowed.
storeURL
A dictionary containing key-value pairs that specify whether the store should be read-only, and whether (for an XML store) the XML file should be validated against the DTD before it is read. For key definitions, see Store Options (page 293) and Migration Options (page 295). This value may be nil.
error
If a new store cannot be created, upon return contains an instance of NSError that describes the problem Return Value The newly-created store or, if an error occurs, nil. Availability Available in OS X v10.4 and later. See Also
migratePersistentStore:toURL:options:withType:error:
(page 285)
importStoreWithIdentifier:fromExternalRecordsDirectory:toURL:options:withType:error: (page
281)
removePersistentStore:error:
(page 287)
Declared in
NSPersistentStoreCoordinator.h
280
executeRequest:withContext:error:
Sends a request to all the persistent stores associated with the receiver.
- (id)executeRequest:(NSPersistentStoreRequest *)request
Parameters
request
If an error occurs, upon return contains an NSError object that describes the problem. Return Value An array containing managed objects, managed object IDs, or dictionaries as appropriate for a fetch request; an empty array if request is a save request, or nil if an error occurred. User defined requests return arrays of arrays, where a nested array is the result returned from a single store. Availability Available in OS X v10.7 and later. Declared in
NSPersistentStoreCoordinator.h
importStoreWithIdentifier:fromExternalRecordsDirectory:toURL:options:withType: error:
Creates and populates a store with the external records found at a given URL.
- (NSPersistentStore *)importStoreWithIdentifier:(NSString *)storeIdentifier
fromExternalRecordsDirectory:(NSURL *)externalRecordsURL toURL:(NSURL *)destinationURL options:(NSDictionary *)options withType:(NSString *)storeType error:(NSError **)error
Parameters
storeIdentifier
The identifier for a store. If this value is nil then the method imports the records for the first store found.
281
externalRecordsURL
An URL object that specifies the location for the new store. There should be no existing store at this location, as the store will be created from scratch (appending to an existing store is not allowed).
options
A dictionary containing key-value pairs that specify whether the store should be read-only, and whether (for an XML store) the XML file should be validated against the DTD before it is read. For key definitions, see Store Options (page 293).
storeType
A string constant (such as NSSQLiteStoreType) that specifies the type of the new storesee Store Types (page 291).
error
If an error occurs, upon return contains an instance of NSError that describes the problem. Return Value An object representing the newly-created store. Availability Available in OS X v10.6 and later. See Also (page 279) migratePersistentStore:toURL:options:withType:error: (page 285) removePersistentStore:error: (page 287)
addPersistentStoreWithType:configuration:URL:options:error:
Declared in
NSPersistentStoreCoordinator.h
initWithManagedObjectModel:
Initializes the receiver with a managed object model.
- (id)initWithManagedObjectModel:(NSManagedObjectModel *)model
Parameters
model
282
Return Value The receiver, initialized with model. Availability Available in OS X v10.4 and later.
Related Sample Code Core Data Utility
Declared in
NSPersistentStoreCoordinator.h
lock
Attempts to acquire a lock.
- (void)lock
Discussion This method blocks a thread execution s until the lock can be acquired. An application protects a critical section of code by requiring a thread to acquire a lock before executing the code. Once the critical section is past, the thread relinquishes the lock by invoking unlock. Availability Available in OS X v10.4 and later. See Also (page 289) unlock (page 290)
tryLock
Declared in
NSPersistentStoreCoordinator.h
managedObjectIDForURIRepresentation:
Returns an object ID for the specified URI representation of an object ID if a matching store is available, or nil if a matching store cannot be found.
- (NSManagedObjectID *)managedObjectIDForURIRepresentation:(NSURL *)URL
Parameters
URL
283
Return Value An object ID for the object specified by URL. Discussion The URI representation contains a UUID of the store the ID is coming from, and the coordinator can match it against the stores added to it. Availability Available in OS X v10.4 and later. See Also
URIRepresentation (page 222) (NSManagedObjectID) objectWithID: (page 199) (NSManagedObjectContext)
Declared in
NSPersistentStoreCoordinator.h
managedObjectModel
Returns the receivers managed object model.
- (NSManagedObjectModel *)managedObjectModel
Return Value The receivers managed object model. Availability Available in OS X v10.4 and later. Declared in
NSPersistentStoreCoordinator.h
metadataForPersistentStore:
Returns a dictionary that contains the metadata currently stored or to-be-stored in a given persistent store.
- (NSDictionary *)metadataForPersistentStore:(NSPersistentStore *)store
Parameters
store
A persistent store.
284
Return Value A dictionary that contains the metadata currently stored or to-be-stored in store. Availability Available in OS X v10.4 and later. See Also
setMetadata:forPersistentStore:
(page 288)
Declared in
NSPersistentStoreCoordinator.h
migratePersistentStore:toURL:options:withType:error:
Moves a persistent store to a new location, changing the storage type if necessary.
- (NSPersistentStore *)migratePersistentStore:(NSPersistentStore *)store toURL:(NSURL
Parameters
store
A persistent store.
URL
An URL object that specifies the location for the new store.
options
A dictionary containing key-value pairs that specify whether the store should be read-only, and whether (for an XML store) the XML file should be validated against the DTD before it is read. For key definitions, see Store Options (page 293).
storeType
A string constant (such as NSSQLiteStoreType) that specifies the type of the new storesee Store Types (page 291).
error
If an error occurs, upon return contains an instance of NSError that describes the problem. Return Value If the migration is successful, the new store, otherwise nil.
285
Discussion This method is typically used for Save As operations. Performance may vary depending on the type of old and new store. For more details of the action of this method, see Persistent Store Features in Core Data Programming Guide . Important: After invocation of this method, the specified store is removed from the coordinator thus store is no longer a useful reference. Availability Available in OS X v10.4 and later. See Also
addPersistentStoreWithType:configuration:URL:options:error: removePersistentStore:error:
(page 279)
(page 287)
Declared in
NSPersistentStoreCoordinator.h
persistentStoreForURL:
Returns the persistent store for the specified URL.
- (NSPersistentStore *)persistentStoreForURL:(NSURL *)URL
Parameters
URL
An URL object that specifies the location of a persistent store. Return Value The persistent store at the location specified by URL. Availability Available in OS X v10.4 and later. See Also (page 287) URLForPersistentStore: (page 290)
persistentStores
286
Declared in
NSPersistentStoreCoordinator.h
persistentStores
Returns an array of persistent stores associated with the receiver.
- (NSArray *)persistentStores
Return Value An array persistent stores associated with the receiver. Availability Available in OS X v10.4 and later. See Also (page 286) URLForPersistentStore: (page 290)
persistentStoreForURL:
Declared in
NSPersistentStoreCoordinator.h
removePersistentStore:error:
Removes a given persistent store.
- (BOOL)removePersistentStore:(NSPersistentStore *)store error:(NSError **)error
Parameters
store
A persistent store.
error
If an error occurs, upon return contains an instance of NSError that describes the problem. Return Value YES if the store is removed, otherwise NO. Availability Available in OS X v10.4 and later. See Also (page 279) migratePersistentStore:toURL:options:withType:error: (page 285)
addPersistentStoreWithType:configuration:URL:options:error:
287
Declared in
NSPersistentStoreCoordinator.h
setMetadata:forPersistentStore:
Sets the metadata stored in the persistent store during the next save operation executed on it to metadata.
- (void)setMetadata:(NSDictionary *)metadata forPersistentStore:(NSPersistentStore
*)store
Parameters
metadata
A persistent store. Discussion The store type and UUID (NSStoreTypeKey and NSStoreUUIDKey) are always added automatically, however NSStoreUUIDKey is only added if it is not set manually as part of the dictionary argument. Important: Setting the metadata for a store does not change the information on disk until the store is actually saved. Availability Available in OS X v10.4 and later. See Also
metadataForPersistentStore:
(page 284)
Declared in
NSPersistentStoreCoordinator.h
setURL:forPersistentStore:
Sets the URL for a given persistent store.
288
Parameters
url
A persistent store associated with the receiver. Return Value YES if the store was relocated, otherwise NO. Discussion For atomic stores, this method alters the location to which the next save operation will write the file; for non-atomic stores, invoking this method will relinquish the existing connection and create a new one at the specified URL. (For non-atomic stores, a store must already exist at the destination URL; a new store will not be created.) Availability Available in OS X v10.5 and later.
Related Sample Code File Wrappers with Core Data Documents
Declared in
NSPersistentStoreCoordinator.h
tryLock
Attempts to acquire a lock.
- (BOOL)tryLock
Return Value YES if successful, otherwise NO. Discussion Returns immediatelycontrast lock (page 283) which blocks. Availability Available in OS X v10.4 and later. See Also lock (page 283)
289
unlock
(page 290)
Declared in
NSPersistentStoreCoordinator.h
unlock
Relinquishes a previously acquired lock.
- (void)unlock
Availability Available in OS X v10.4 and later. See Also lock (page 283) tryLock (page 289) Declared in
NSPersistentStoreCoordinator.h
URLForPersistentStore:
Returns the URL for a given persistent store.
- (NSURL *)URLForPersistentStore:(NSPersistentStore *)store
Parameters
store
A persistent store. Return Value The URL for store. Availability Available in OS X v10.4 and later. See Also (page 286) persistentStores (page 287)
persistentStoreForURL:
Declared in
NSPersistentStoreCoordinator.h
290
Constants
Store Types
Types of persistent store.
* * * *
Constants
NSSQLiteStoreType
The SQLite database store type. Available in OS X v10.4 and later. Declared in NSPersistentStoreCoordinator.h.
NSXMLStoreType
The XML store type. Available in OS X v10.4 and later. Declared in NSPersistentStoreCoordinator.h.
NSBinaryStoreType
The binary store type. Available in OS X v10.4 and later. Declared in NSPersistentStoreCoordinator.h.
NSInMemoryStoreType
The in-memory store type. Available in OS X v10.4 and later. Declared in NSPersistentStoreCoordinator.h.
Store Metadata
Keys used in a store metadata s dictionary.
291
Constants
NSStoreTypeKey
The key in the metadata dictionary to identify the store type. Available in OS X v10.4 and later. Declared in NSPersistentStoreCoordinator.h.
NSStoreUUIDKey
The key in the metadata dictionary to identify the store UUID. The store UUID is useful to identify stores through URI representations, but it is not guaranteed to be unique. The UUID generated for new stores is uniqueusers can freely copy files and thus the UUID stored insideso if you track or reference stores explicitly you need to be aware of duplicate UUIDs and potentially override the UUID when a new store is added to the list of known stores in your application. Available in OS X v10.4 and later. Declared in NSPersistentStoreCoordinator.h.
Constants
NSAddedPersistentStoresKey
Key for the array of stores that were added. Available in OS X v10.4 and later. Declared in NSPersistentStoreCoordinator.h.
NSRemovedPersistentStoresKey
Key for the array of stores that were removed. Available in OS X v10.4 and later. Declared in NSPersistentStoreCoordinator.h.
NSUUIDChangedPersistentStoresKey
Key for the array of stores whose UUIDs changed. Available in OS X v10.4 and later. Declared in NSPersistentStoreCoordinator.h.
292
Store Options
Keys for the options dictionary used in
addPersistentStoreWithType:configuration:URL:options:error: (page 279), migratePersistentStore:toURL:options:withType:error: (page 285), and importStoreWithIdentifier:fromExternalRecordsDirectory:toURL:options:withType: error: (page
281).
NSString NSString NSString NSString NSString NSString NSString NSString NSString NSString NSString
* * * * * * * * * * *
const const const const const const const const const const const
NSReadOnlyPersistentStoreOption; NSValidateXMLStoreOption; NSPersistentStoreTimeoutOption; NSSQLitePragmasOption; NSSQLiteAnalyzeOption; NSSQLiteManualVacuumOption; NSExternalRecordsDirectoryOption; NSExternalRecordExtensionOption; NSExternalRecordsFileFormatOption; NSPersistentStoreUbiquitousContentNameKey; NSPersistentStoreUbiquitousContentURLKey;
Constants
NSReadOnlyPersistentStoreOption
A flag that indicates whether a store is treated as read-only or not. The default value is NO. Available in OS X v10.4 and later. Declared in NSPersistentStoreCoordinator.h.
NSValidateXMLStoreOption
A flag that indicates whether an XML file should be validated with the DTD while opening. The default value is NO. Available in OS X v10.4 and later. Declared in NSPersistentStoreCoordinator.h.
NSPersistentStoreTimeoutOption
Options key that specifies the connection timeout for Core Data stores. The corresponding value is an NSNumber object that represents the duration in seconds that Core Data will wait while attempting to create a connection to a persistent store. If a connection is cannot be made within that timeframe, the operation is aborted and an error is returned. Available in OS X v10.5 and later. Declared in NSPersistentStoreCoordinator.h.
293
NSSQLitePragmasOption
Options key for a dictionary of SQLite pragma settings with pragma values indexed by pragma names as keys. All pragma values must be specified as NSString objects. The fullfsync and synchronous pragmas control the tradeoff between write performance (write to disk speed & cache utilization) and durability (data loss/corruption sensitivity to power interruption). For more information on pragma settings, see http://sqlite.org/pragma.html. Available in OS X v10.5 and later. Declared in NSPersistentStoreCoordinator.h.
NSSQLiteAnalyzeOption
Option key to run an analysis of the store data to optimize indices based on statistical information when the store is added to the coordinator. This invokes SQLite's ANALYZE command. It is ignored by stores other than the SQLite store. Available in OS X v10.6 and later. Declared in NSPersistentStoreCoordinator.h.
NSSQLiteManualVacuumOption
Option key to rebuild the store file, forcing a database wide defragmentation when the store is added to the coordinator. This invokes SQLite's VACUUM command. It is ignored by stores other than the SQLite store. Available in OS X v10.6 and later. Declared in NSPersistentStoreCoordinator.h.
NSExternalRecordsDirectoryOption
Option indicating the directory where Spotlight external record files should be written to. Available in OS X v10.6 and later. Declared in NSPersistentStoreCoordinator.h.
NSExternalRecordExtensionOption
Option indicating the file extension to use for Spotlight external record files. Available in OS X v10.6 and later. Declared in NSPersistentStoreCoordinator.h.
NSExternalRecordsFileFormatOption
Option to specify the file format of a Spotlight external records. For possible values, see Spotlight External Record File Format Options (page 297). Available in OS X v10.6 and later. Declared in NSPersistentStoreCoordinator.h.
294
NSPersistentStoreUbiquitousContentNameKey
Option to specify that a persistent store has a given name in ubiquity. This option is required for ubiquitous content to function. Available in OS X v10.7 and later. Declared in NSPersistentStoreCoordinator.h.
NSPersistentStoreUbiquitousContentURLKey
Option to specify the log path to use for ubiquitous content logs. This option is required for ubiquitous content to function. Available in OS X v10.7 and later. Declared in NSPersistentStoreCoordinator.h.
Migration Options
Migration options, specified in the dictionary of options when adding a persistent store using addPersistentStoreWithType:configuration:URL:options:error: (page 279).
Constants
NSIgnorePersistentStoreVersioningOption
Key to ignore the built-in versioning provided by Core Data. The corresponding value is an NSNumber object. If the boolValue of the number is YES, Core Data will not compare the version hashes between the managed object model in the coordinator and the metadata for the loaded store. (It will, however, continue to update the version hash information in the metadata.) This key and corresponding value of YES is specified by default for all applications linked on or before OS X v10.4. Available in OS X v10.5 and later. Declared in NSPersistentStoreCoordinator.h.
NSMigratePersistentStoresAutomaticallyOption
Key to automatically attempt to migrate versioned stores. The corresponding value is an NSNumber object. If the boolValue of the number is YES and if the version hash information for the added store is determined to be incompatible with the model for the coordinator, Core Data will attempt to locate the source and mapping models in the application bundles, and perform a migration. Available in OS X v10.5 and later. Declared in NSPersistentStoreCoordinator.h.
295
NSInferMappingModelAutomaticallyOption
Key to attempt to create the mapping model automatically. The corresponding value is an NSNumber object. If the boolValue of the number is YES and the value of the NSMigratePersistentStoresAutomaticallyOption is YES, the coordinator will attempt to infer a mapping model if none can be found. Available in OS X v10.6 and later. Declared in NSPersistentStoreCoordinator.h.
Versioning Support
Keys in store metadata to support versioning.
Constants
NSStoreModelVersionHashesKey
Key to represent the version hash information for the model used to create the store. This key is used in the metadata for a persistent store. Available in OS X v10.5 and later. Declared in NSPersistentStoreCoordinator.h.
NSStoreModelVersionIdentifiersKey
Key to represent the version identifiers for the model used to create the store. If you add your own annotations to a models version identifier (see versionIdentifiers (page 241)), they are stored in the persistent stores metadata. You can use this key to retrieve the identifiers from the metadata dictionaries available from NSPersistentStore (metadata (page 267)) and NSPersistentStoreCoordinator (metadataForPersistentStore: (page 284) and related methods). The corresponding value is a Foundation collection (an NSArray or NSSet object). Available in OS X v10.5 and later. Declared in NSPersistentStoreCoordinator.h.
296
NSPersistentStoreOSCompatibility
Key to represent the earliest version of the operation system that the persistent store supports. The corresponding value is an NSNumber object that takes the form of the constants defined by the availability macros defined in /usr/include/AvailabilityMacros.h; for example 1040 represents OS X version 10.4.0. Backward compatibility may preclude some features. Available in OS X v10.5 and later. Declared in NSPersistentStoreCoordinator.h.
Constants
NSXMLExternalRecordType
Specifies an XML file format. Available in OS X v10.6 and later. Declared in NSPersistentStoreCoordinator.h.
NSBinaryExternalRecordType
Specifies a binary file format Available in OS X v10.6 and later. Declared in NSPersistentStoreCoordinator.h.
* * * * *
297
Constants
NSEntityNameInPathKey
Dictionary key for the entity name extracted from an external record file. Available in OS X v10.6 and later. Declared in NSPersistentStoreCoordinator.h.
NSStoreUUIDInPathKey
Dictionary key for the store UUID extracted from an external record file. Available in OS X v10.6 and later. Declared in NSPersistentStoreCoordinator.h.
NSStorePathKey
Dictionary key for the store path (an instance of NSURL) extracted from an external record file. This is resolved to the store-file path contained in the an external record file directory. Available in OS X v10.6 and later. Declared in NSPersistentStoreCoordinator.h.
NSModelPathKey
Dictionary key for the managed object model path (an instance of NSURL) extracted from an external record file. This is resolved to the model.mom path contained in the external record file directory. Available in OS X v10.6 and later. Declared in NSPersistentStoreCoordinator.h.
NSObjectURIKey
Dictionary key for the object URI extracted from an external record file. Available in OS X v10.6 and later. Declared in NSPersistentStoreCoordinator.h.
Notifications
NSPersistentStoreCoordinatorStoresDidChangeNotification
Posted whenever persistent stores are added to or removed from a persistent store coordinator, or when store UUIDs change. The notification's object is the persistent store coordinator that was affected. The notifications userInfo dictionary contains information about the stores that were added or removed, specified using the following keys:
298
Key for the array of stores that were added. Key for the array of stores that were removed. Key for the array of stores whose UUIDs changed.
NSPersistentStoreCoordinatorWillRemoveStoreNotification
Posted whenever a persistent store is removed from a persistent store coordinator. The notification is sent during the invocation of NSPersistentStores willRemoveFromPersistentStoreCoordinator: (page 270) method during store deallocation or removal. The notification's object is the persistent store coordinator will be removed. Availability Available in OS X v10.6 and later. Declared in
NSPersistentStoreCoordinator.h
NSPersistentStoreDidImportUbiquitousContentChangesNotification
Posted after records are imported from the ubiquitous content store. The notifications object is set to the NSPersistentStoreCoordinator instance which registered the store. Availability Available in OS X v10.7 and later. Declared in
NSPersistentStoreCoordinator.h
299
/System/Library/Frameworks/CoreData.framework Available in OS X v10.7 and later. CoreData/NSPersistentStoreRequest.h Core Data Programming Guide
Overview
An instance of NSPersistentStoreRequest describes criteria used to retrieve data from or save data to persistent stores.
Tasks
Fetch Attributes
affectedStores
(page 301) Returns the stores the request should be sent to. (page 301) Sets the stores the request should be sent to. (page 301) Returns the type of the fetch request.
setAffectedStores:
requestType
300
Instance Methods
affectedStores
Returns the stores the request should be sent to.
- (NSArray *)affectedStores
Return Value The stores the request should be sent to. Discussion The array contains instances of NSPersistentStore. Availability Available in OS X v10.7 and later. Declared in
NSPersistentStoreRequest.h
requestType
Returns the type of the fetch request.
- (NSPersistentStoreRequestType)requestType
Return Value The type of the fetch request. Discussion For possible values, see NSFetchRequestResultType (page 302). Availability Available in OS X v10.7 and later. Declared in
NSPersistentStoreRequest.h
setAffectedStores:
Sets the stores the request should be sent to.
- (void)setAffectedStores:(NSArray *)stores
301
Parameters
stores
The stores the request should be sent to. The array should contain instances of NSPersistentStore. Discussion Availability Available in OS X v10.7 and later. Declared in
NSPersistentStoreRequest.h
Constants
NSFetchRequestResultType
These constants specify the types of fetch request.
Constants
NSFetchRequestType
Specifies that the request returns managed objects. Available in OS X v10.7 and later. Declared in NSPersistentStoreRequest.h.
NSSaveRequestType
Specifies that the request. Available in OS X v10.7 and later. Declared in NSPersistentStoreRequest.h. Discussion These constants are used by requestType (page 301).
302
/System/Library/Frameworks/CoreData.framework Available in OS X v10.4 and later. CoreData/NSPropertyDescription.h Core Data Programming Guide
Overview
The NSPropertyDescription class is used to define properties of an entity in a Core Data managed object model. Properties are to entities what instance variables are to classes. A property describes a single value within an object managed by the Core Data Framework. There are different types of property, each represented by a subclass which encapsulates the specific property behaviorsee NSAttributeDescription, NSRelationshipDescription, and NSFetchedPropertyDescription. Note that a property name cannot be the same as any no-parameter method name of NSObject or NSManagedObject. For example, you cannot give a property the name "description". There are hundreds of methods on NSObject which may conflict with property namesand this list can grow without warning from frameworks or other libraries. You should avoid very general words (like "font , and color) and words or phrases which overlap with Cocoa paradigms (such as isEditing and objectSpecifier). Propertiesrelationships as well as attributesmay be transient. A managed object context knows about transient properties and tracks changes made to them. Transient properties are ignored by the persistent store, and not just during saves: you cannot fetch using a predicate based on transients (although you can use transient properties to filter in memory yourself ).
303
Tasks
Getting Features of a Property
entity
(page 306) Returns the entity description of the receiver. (page 306) Returns a Boolean value that indicates whether the receiver is important for searching. (page 307) Returns a Boolean value that indicates whether the receiver is optional. (page 308) Returns a Boolean value that indicates whether the receiver is transient. (page 309) Returns the name of the receiver. (page 316) Returns the user info dictionary of the receiver.
isIndexed
isOptional
isTransient
name
userInfo
(page 310) Sets the optionality flag of the receiver. (page 311) Sets the name of the receiver. (page 312) Sets the optionality flag of the receiver.
setName:
setOptional:
304
setTransient:
(page 314) Sets the transient flag of the receiver. (page 314) Sets the user info dictionary of the receiver.
setUserInfo:
Validation
validationPredicates
(page 317) Returns the validation predicates of the receiver. (page 317) Returns the error strings associated with the receivers validation predicates. (page 315) Sets the validation predicates and warnings of the receiver.
validationWarnings
setValidationPredicates:withValidationWarnings:
Versioning Support
versionHash
(page 317) Returns the version hash for the receiver. (page 318) Returns the version hash modifier for the receiver. (page 316) Sets the version hash modifier for the receiver. (page 309) Returns the renaming identifier for the receiver. (page 313) Sets the renaming identifier for the receiver.
versionHashModifier
setVersionHashModifier:
renamingIdentifier
setRenamingIdentifier:
Spotlight Support
isIndexedBySpotlight
(page 307) Returns a Boolean value that indicates whether the property should be indexed by Spotlight. (page 311) Sets whether the property should be indexed by Spotlight.
setIndexedBySpotlight:
305
isStoredInExternalRecord
(page 308) Returns a Boolean value that indicates whether the property data should be written out in an external record file corresponding to the managed object. (page 313) Sets whether the data should be written out in an external record file corresponding to the managed object.
setStoredInExternalRecord:
Instance Methods
entity
Returns the entity description of the receiver.
- (NSEntityDescription *)entity
Return Value The entity description of the receiver. Availability Available in OS X v10.4 and later. See Also
setProperties: (page 54) (NSEntityDescription)
Declared in
NSPropertyDescription.h
isIndexed
Returns a Boolean value that indicates whether the receiver is important for searching.
- (BOOL)isIndexed
Return Value YES if the receiver is important for searching, otherwise NO. Discussion Object stores can optionally use this information upon store creation for operations such as defining indexes.
306
(page 310)
Declared in
NSPropertyDescription.h
isIndexedBySpotlight
Returns a Boolean value that indicates whether the property should be indexed by Spotlight.
- (BOOL)isIndexedBySpotlight
Return Value YES if the property should be indexed by Spotlight, otherwise NO. Discussion For details, see Core Data Spotlight Integration Programming Guide . Special Considerations This property has no effect on iOS. Availability Available in OS X v10.6 and later. See Also
setIndexedBySpotlight:
(page 311)
Declared in
NSPropertyDescription.h
isOptional
Returns a Boolean value that indicates whether the receiver is optional.
- (BOOL)isOptional
307
(page 312)
Declared in
NSPropertyDescription.h
isStoredInExternalRecord
Returns a Boolean value that indicates whether the property data should be written out in an external record file corresponding to the managed object.
- (BOOL)isStoredInExternalRecord
Return Value YES if the property data should be written out in an external record file corresponding to the managed object, otherwise NO. Discussion For details, see Core Data Spotlight Integration Programming Guide . Special Considerations This property has no effect on iOS. Availability Available in OS X v10.6 and later. See Also
setStoredInExternalRecord:
(page 313)
Declared in
NSPropertyDescription.h
isTransient
Returns a Boolean value that indicates whether the receiver is transient.
- (BOOL)isTransient
308
Return Value YES if the receiver is transient, otherwise NO. Availability Available in OS X v10.4 and later. See Also
setTransient:
(page 314)
Declared in
NSPropertyDescription.h
name
Returns the name of the receiver.
- (NSString *)name
Return Value The name of the receiver. Availability Available in OS X v10.4 and later. See Also
setName:
(page 311)
Declared in
NSPropertyDescription.h
renamingIdentifier
Returns the renaming identifier for the receiver.
- (NSString *)renamingIdentifier
309
Discussion This is used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will return the property's name. Availability Available in OS X v10.6 and later. See Also
setRenamingIdentifier:
(page 313)
Declared in
NSPropertyDescription.h
setIndexed:
Sets the optionality flag of the receiver.
- (void)setIndexed:(BOOL)flag
Parameters
flag
A Boolean value that indicates whether whether the receiver is important for searching (YES) or not (NO). Discussion Object stores can optionally use this information upon store creation for operations such as defining indexes. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.5 and later. See Also
isIndexed
(page 306)
Declared in
NSPropertyDescription.h
310
setIndexedBySpotlight:
Sets whether the property should be indexed by Spotlight.
- (void)setIndexedBySpotlight:(BOOL)flag
Parameters
flag YES if the property should be indexed by Spotlight, otherwise NO.
Discussion For details, see Core Data Spotlight Integration Programming Guide . Special Considerations This property has no effect on iOS. Availability Available in OS X v10.6 and later. See Also
isIndexedBySpotlight
(page 307)
Declared in
NSPropertyDescription.h
setName:
Sets the name of the receiver.
- (void)setName:(NSString *)name
Parameters
name
The name of the receiver. Special Considerations A property name cannot be the same as any no-parameter method name of NSObject or NSManagedObject. Since there are hundreds of methods on NSObject which may conflict with property names, you should avoid very general words (like "font , and color) and words or phrases which overlap with Cocoa paradigms (such as isEditing and objectSpecifier). This method raises an exception if the receivers model has been used by an object graph manager.
311
Availability Available in OS X v10.4 and later. See Also name (page 309)
Related Sample Code Core Data Utility
Declared in
NSPropertyDescription.h
setOptional:
Sets the optionality flag of the receiver.
- (void)setOptional:(BOOL)flag
Parameters
flag
A Boolean value that indicates whether whether the receiver is optional (YES) or not (NO). Discussion The optionality flag specifies whether a propertys value can be nil before an object can be saved to a persistent store. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also
isOptional
(page 307)
Declared in
NSPropertyDescription.h
312
setRenamingIdentifier:
Sets the renaming identifier for the receiver.
- (void)setRenamingIdentifier:(NSString *)value
Parameters
value
The renaming identifier for the receiver. Discussion See renamingIdentifier (page 309) for a full discussion. Availability Available in OS X v10.6 and later. See Also
renamingIdentifier
(page 309)
Declared in
NSPropertyDescription.h
setStoredInExternalRecord:
Sets whether the data should be written out in an external record file corresponding to the managed object.
- (void)setStoredInExternalRecord:(BOOL)flag
Parameters
flag YES if the property data should be written out in an external record file corresponding to the managed
object, otherwise NO. Discussion For details, see Core Data Spotlight Integration Programming Guide . Special Considerations This property has no effect on iOS. Availability Available in OS X v10.6 and later. See Also
isStoredInExternalRecord
(page 308)
313
Declared in
NSPropertyDescription.h
setTransient:
Sets the transient flag of the receiver.
- (void)setTransient:(BOOL)flag
Parameters
flag
A Boolean value that indicates whether whether the receiver is transient (YES) or not (NO). Discussion The transient flag specifies whether or not a propertys value is ignored when an object is saved to a persistent store. Transient properties are not saved to the persistent store, but are still managed for undo, redo, validation, and so on. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also
isTransient
(page 308)
Declared in
NSPropertyDescription.h
setUserInfo:
Sets the user info dictionary of the receiver.
- (void)setUserInfo:(NSDictionary *)dictionary
Parameters
dictionary
The user info dictionary of the receiver. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager.
314
(page 316)
Declared in
NSPropertyDescription.h
setValidationPredicates:withValidationWarnings:
Sets the validation predicates and warnings of the receiver.
- (void)setValidationPredicates:(NSArray *)validationPredicates
withValidationWarnings:(NSArray *)validationWarnings
Parameters
validationPredicates
An array containing the validation warnings for the receiver. Discussion The validationPredicates and validationWarnings arrays should contain the same number of elements, and corresponding elements should appear at the same index in each array. Instead of implementing individual validation methods, you can use this method to provide a list of predicates that are evaluated against the managed objects and a list of corresponding error messages (which can be localized). Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also
validationPredicates validationWarnings
315
Declared in
NSPropertyDescription.h
setVersionHashModifier:
Sets the version hash modifier for the receiver.
- (void)setVersionHashModifier:(NSString *)modifierString
Parameters
modifierString
The version hash modifier for the receiver. Discussion See versionHashModifier (page 318) for a full discussion. Availability Available in OS X v10.5 and later. See Also
versionHash versionHashModifier
Declared in
NSPropertyDescription.h
userInfo
Returns the user info dictionary of the receiver.
- (NSDictionary *)userInfo
Return Value The user info dictionary of the receiver. Availability Available in OS X v10.4 and later. See Also
setUserInfo:
(page 314)
Declared in
NSPropertyDescription.h
316
validationPredicates
Returns the validation predicates of the receiver.
- (NSArray *)validationPredicates
Return Value An array containing the receivers validation predicates. Availability Available in OS X v10.4 and later. See Also
validationWarnings
setValidationPredicates:withValidationWarnings:
Declared in
NSPropertyDescription.h
validationWarnings
Returns the error strings associated with the receivers validation predicates.
- (NSArray *)validationWarnings
Return Value An array containing the error strings associated with the receivers validation predicates. Availability Available in OS X v10.4 and later. See Also
validationPredicates
setValidationPredicates:withValidationWarnings:
Declared in
NSPropertyDescription.h
versionHash
Returns the version hash for the receiver.
- (NSData *)versionHash
317
Return Value The version hash for the receiver. Discussion The version hash is used to uniquely identify a property based on its configuration. The version hash uses only values which affect the persistence of data and the user-defined versionHashModifier (page 318) value. (The values which affect persistence are the name of the property, and the flags for isOptional, isTransient, and isReadOnly.) This value is stored as part of the version information in the metadata for stores, as well as a definition of a property involved in an NSPropertyMapping object. Availability Available in OS X v10.5 and later. See Also (page 318) setVersionHashModifier: (page 316)
versionHashModifier
Declared in
NSPropertyDescription.h
versionHashModifier
Returns the version hash modifier for the receiver.
- (NSString *)versionHashModifier
Return Value The version hash modifier for the receiver. Discussion This value is included in the version hash for the property. You use it to mark or denote a property as being a different version than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the attributes of a property are unchanged but the format or content of its data are changed.) This value is included in the version hash for the property. Availability Available in OS X v10.5 and later. See Also
versionHash
setVersionHashModifier:
318
Declared in
NSPropertyDescription.h
319
NSObject NSObject (NSObject) /System/Library/Frameworks/CoreData.framework Available in OS X v10.5 and later. CoreData/NSPropertyMapping.h Core Data Model Versioning and Data Migration Programming Guide
Overview
Instances of NSPropertyMapping specify in a mapping model how to map from a property in a source entity to a property in a destination entity.
Tasks
Managing Mapping Attributes
name
(page 321) Returns the name of the property in the destination entity for the receiver. (page 321) Sets the name of the property in the destination entity for the receiver. (page 323) Returns the value expression for the receiver. (page 322) Sets the value expression for the receiver. (page 322) Returns the user info for the receiver.
setName:
valueExpression
setValueExpression:
userInfo
320
setUserInfo:
Instance Methods
name
Returns the name of the property in the destination entity for the receiver.
- (NSString *)name
Return Value The name of the property in the destination entity for the receiver. Availability Available in OS X v10.5 and later. See Also
setName:
(page 321)
Declared in
NSPropertyMapping.h
setName:
Sets the name of the property in the destination entity for the receiver.
- (void)setName:(NSString *)name
Parameters
name
The name of the property in the destination entity for the receiver. Availability Available in OS X v10.5 and later. See Also name (page 321) Declared in
NSPropertyMapping.h
321
setUserInfo:
Sets the user info for the receiver.
- (void)setUserInfo:(NSDictionary *)userInfo
Parameters
userInfo
The user info for the receiver. Availability Available in OS X v10.5 and later. See Also
userInfo
(page 322)
Declared in
NSPropertyMapping.h
setValueExpression:
Sets the value expression for the receiver.
- (void)setValueExpression:(NSExpression *)expression
Parameters
expression
The the value expression for the receiver. Availability Available in OS X v10.5 and later. See Also
setValueExpression:
(page 322)
Declared in
NSPropertyMapping.h
userInfo
Returns the user info for the receiver.
- (NSDictionary *)userInfo
322
Return Value The user info for the receiver. Availability Available in OS X v10.5 and later. See Also
setUserInfo:
(page 322)
Declared in
NSPropertyMapping.h
valueExpression
Returns the value expression for the receiver.
- (NSExpression *)valueExpression
Return Value The value expression for the receiver. Discussion The expression is used to create the value for the destination property. Availability Available in OS X v10.5 and later. See Also
setValueExpression:
(page 322)
Declared in
NSPropertyMapping.h
323
/System/Library/Frameworks/CoreData.framework Available in OS X v10.4 and later. CoreData/NSRelationshipDescription.h Core Data Programming Guide
Overview
The NSRelationshipDescription class is used to describe relationships of an entity in an NSEntityDescription object.
NSRelationshipDescription extends NSPropertyDescription to describe features appropriate to
relationships, including cardinality (the number of objects allowed in the relationship), the destination entity, and delete rules.
Cardinality
The maximum and minimum counts for a relationship indicate the number of objects referenced (1 for a to-one relationship, -1 means undefined). The counts are only enforced if the relationship value in the containing object is not nil. That is, provided that the relationship value is optional, there may be zero objects in the relationship, which might be less than the minimum count.
324
Tasks
Managing Type Information
destinationEntity
(page 327) Returns the entity description of the receiver's destination. (page 330) Sets the entity description for the receiver's destination. (page 327) Returns the relationship that represents the inverse of the receiver. (page 331) Sets the inverse relationship of the receiver.
setDestinationEntity:
inverseRelationship
setInverseRelationship:
(page 326) Returns the delete rule of the receiver. (page 330) Sets the delete rule of the receiver.
setDeleteRule:
Cardinality
maxCount
(page 329) Returns the maximum count of the receiver. (page 331) Sets the maximum count of the receiver.
setMaxCount:
325
minCount
(page 329) Returns the minimum count of the receiver. (page 332) Sets the minimum count of the receiver. (page 328) Returns a Boolean value that indicates whether the receiver represents a to-many relationship.
setMinCount:
isToMany
Ordering
isOrdered
(page 328) Returns a Boolean value that indicates whether the receiver describes an ordered relationship. (page 332) Sets whether the receiver describes an ordered relationship.
setOrdered:
Versioning Support
versionHash
Instance Methods
deleteRule
Returns the delete rule of the receiver.
- (NSDeleteRule)deleteRule
Return Value The receivers delete rule. Availability Available in OS X v10.4 and later. See Also
setDeleteRule:
(page 330)
326
Declared in
NSRelationshipDescription.h
destinationEntity
Returns the entity description of the receiver's destination.
- (NSEntityDescription *)destinationEntity
Return Value The entity description for the receiver's destination. Availability Available in OS X v10.4 and later. See Also
setDestinationEntity:
(page 330)
Declared in
NSRelationshipDescription.h
inverseRelationship
Returns the relationship that represents the inverse of the receiver.
- (NSRelationshipDescription *)inverseRelationship
Return Value The relationship that represents the inverse of the receiver. Discussion Given a to-many relationship employees between a Department entity and an Employee entity (a department may have many employees), and a to-one relationship department between an Employee entity and a Department entity (an employee may belong to only one department), the inverse of the department relationship is the employees relationship. Availability Available in OS X v10.4 and later. See Also
setInverseRelationship:
(page 331)
327
Declared in
NSRelationshipDescription.h
isOrdered
Returns a Boolean value that indicates whether the receiver describes an ordered relationship.
- (BOOL)isOrdered
Return Value YES if the relationship is ordered, otherwise NO. Availability Available in OS X v10.7 and later. See Also
setOrdered:
(page 332)
Declared in
NSRelationshipDescription.h
isToMany
Returns a Boolean value that indicates whether the receiver represents a to-many relationship.
- (BOOL)isToMany
Return Value YES if the receiver represents a to-many relationship (its maxCount is greater than 1) otherwise NO. Availability Available in OS X v10.4 and later. See Also (page 329) setMaxCount: (page 331)
maxCount
Declared in
NSRelationshipDescription.h
328
maxCount
Returns the maximum count of the receiver.
- (NSUInteger)maxCount
Return Value The maximum count of the receiver. Availability Available in OS X v10.4 and later. See Also (page 328) minCount (page 329) setMaxCount: (page 331) setMinCount: (page 332)
isToMany
Declared in
NSRelationshipDescription.h
minCount
Returns the minimum count of the receiver.
- (NSUInteger)minCount
Return Value The minimum count of the receiver. Availability Available in OS X v10.4 and later. See Also (page 329) (page 331) setMinCount: (page 332)
maxCount setMaxCount:
Declared in
NSRelationshipDescription.h
329
setDeleteRule:
Sets the delete rule of the receiver.
- (void)setDeleteRule:(NSDeleteRule)rule
Parameters
rule
The delete rule for the receiver. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also
deleteRule
(page 326)
Declared in
NSRelationshipDescription.h
setDestinationEntity:
Sets the entity description for the receiver's destination.
- (void)setDestinationEntity:(NSEntityDescription *)entity
Parameters
entity
The destination entity for the receiver. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also
destinationEntity
(page 327)
Declared in
NSRelationshipDescription.h
330
setInverseRelationship:
Sets the inverse relationship of the receiver.
- (void)setInverseRelationship:(NSRelationshipDescription *)relationship
Parameters
relationship
The inverse relationship for the receiver. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also
inverseRelationship
(page 327)
Declared in
NSRelationshipDescription.h
setMaxCount:
Sets the maximum count of the receiver.
- (void)setMaxCount:(NSUInteger)maxCount
Parameters
maxCount
The maximum count of the receiver. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also (page 328) maxCount (page 329) minCount (page 329) setMinCount: (page 332)
isToMany
331
Declared in
NSRelationshipDescription.h
setMinCount:
Sets the minimum count of the receiver.
- (void)setMinCount:(NSUInteger)minCount
Parameters
minCount
The minimum count of the receiver. Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.4 and later. See Also (page 329) minCount (page 329) setMaxCount: (page 331)
maxCount
Declared in
NSRelationshipDescription.h
setOrdered:
Sets whether the receiver describes an ordered relationship.
- (void)setOrdered:(BOOL)flag
Parameters
flag YES to indicate that the relationship is ordered, otherwise NO.
Special Considerations This method raises an exception if the receivers model has been used by an object graph manager. Availability Available in OS X v10.7 and later.
332
See Also
isOrdered
(page 328)
Declared in
NSRelationshipDescription.h
versionHash
Returns the version hash for the receiver.
- (NSData *)versionHash
Return Value The version hash for the receiver. Discussion The version hash is used to uniquely identify an attribute based on its configuration. This value includes the versionHash (page 317) information from NSPropertyDescription, the name of the destination entity and the inverse relationship, and the min and max count. Availability Available in OS X v10.5 and later. See Also
versionHash (page 317) (NSPropertyDescription)
Declared in
NSRelationshipDescription.h
Constants
NSDeleteRule
These constants define what happens to relationships when an object is deleted.
333
Constants
NSNoActionDeleteRule
If the object is deleted, no modifications are made to objects at the destination of the relationship. If you use this rule, you are responsible for maintaining the integrity of the object graph. This rule is strongly discouraged for all but advanced users. You should normally use NSNullifyDeleteRule instead. Available in OS X v10.4 and later. Declared in NSRelationshipDescription.h.
NSNullifyDeleteRule
If the object is deleted, back pointers from the objects to which it is related are nullified. Available in OS X v10.4 and later. Declared in NSRelationshipDescription.h.
NSCascadeDeleteRule
If the object is deleted, the destination object or objects of this relationship are also deleted. Available in OS X v10.4 and later. Declared in NSRelationshipDescription.h.
NSDenyDeleteRule
If the destination of this relationship is not nil, the delete creates a validation error. Available in OS X v10.4 and later. Declared in NSRelationshipDescription.h. Availability Available in OS X v10.4 and later. Declared in
NSRelationshipDescription.h
334
Constants
335
Framework
CoreData/CoreData.h
Overview
This document describes the constants defined in the Core Data framework and not described in a document for an individual class.
Constants
Error User Info Keys
Keys in the user info dictionary in errors Core Data creates.
Constants
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. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
336
NSValidationObjectErrorKey
Key for the object that failed to validate for a validation error. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSValidationKeyErrorKey
Key for the key that failed to validate for a validation error. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSValidationPredicateErrorKey
For predicate-based validation, key for the predicate for the condition that failed to validate. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSValidationValueErrorKey
If non-nil, the key for the value for the key that failed to validate for a validation error. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSAffectedStoresErrorKey
The key for stores prompting an error. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSAffectedObjectsErrorKey
The key for objects prompting an error. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSPersistentStoreSaveConflictsErrorKey
The key for the array of merge conflict objects (instances of NSMergeConflict). Available in OS X v10.7 and later. Declared in CoreDataErrors.h.
Error Domain
Constant to identify the SQLite error domain.
337
Constants
NSSQLiteErrorDomain
Domain for SQLite errors. The value of "code" corresponds to preexisting values in SQLite. Available in OS X v10.5 and later. Declared in CoreDataErrors.h.
NSManagedObjectValidationError NSValidationMultipleErrorsError NSValidationMissingMandatoryPropertyError NSValidationRelationshipLacksMinimumCountError NSValidationRelationshipExceedsMaximumCountError NSValidationRelationshipDeniedDeleteError NSValidationNumberTooLargeError NSValidationNumberTooSmallError NSValidationDateTooLateError NSValidationDateTooSoonError NSValidationInvalidDateError NSValidationStringTooLongError NSValidationStringTooShortError NSValidationStringPatternMatchingError
= = = = = = = = = = = = = =
1550, 1560, 1570, 1580, 1590, 1600, 1610, 1620, 1630, 1640, 1650, 1660, 1670, 1680,
Constants
NSManagedObjectValidationError
Error code to denote a generic validation error. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSValidationMultipleErrorsError
Error code to denote an error containing multiple validation errors. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSValidationMissingMandatoryPropertyError
Error code for a non-optional property with a nil value. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
338
NSValidationRelationshipLacksMinimumCountError
Error code to denote a to-many relationship with too few destination objects. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSValidationRelationshipExceedsMaximumCountError
Error code to denote a bounded to-many relationship with too many destination objects. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSValidationRelationshipDeniedDeleteError
Error code to denote some relationship with delete rule NSDeleteRuleDeny is non-empty. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSValidationNumberTooLargeError
Error code to denote some numerical value is too large. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSValidationNumberTooSmallError
Error code to denote some numerical value is too small. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSValidationDateTooLateError
Error code to denote some date value is too late. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSValidationDateTooSoonError
Error code to denote some date value is too soon. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSValidationInvalidDateError
Error code to denote some date value fails to match date pattern. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSValidationStringTooLongError
Error code to denote some string value is too long. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
339
NSValidationStringTooShortError
Error code to denote some string value is too short. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSValidationStringPatternMatchingError
Error code to denote some string value fails to match some pattern. Available in OS X v10.4 and later. Declared in CoreDataErrors.h. Discussion For additional error codes, including NSValidationErrorMinimum and NSValidationErrorMaximum, see NSError.
= = = = =
Constants
NSManagedObjectContextLockingError
Error code to denote an inability to acquire a lock in a managed object context. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSPersistentStoreCoordinatorLockingError
Error code to denote an inability to acquire a lock in a persistent store. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSManagedObjectReferentialIntegrityError
Error code to denote an attempt to fire a fault pointing to an object that does not exist. The store is accessible, but the object corresponding to the fault cannot be found. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
340
NSManagedObjectExternalRelationshipError
Error code to denote that an object being saved has a relationship containing an object from another store. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSManagedObjectMergeError
Error code to denote that a merge policy failedCore Data is unable to complete merging. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSPersistentStoreInvalidTypeError NSPersistentStoreTypeMismatchError NSPersistentStoreIncompatibleSchemaError NSPersistentStoreSaveError NSPersistentStoreIncompleteSaveError NSPersistentStoreSaveConflictsError NSPersistentStoreOperationError NSPersistentStoreOpenError NSPersistentStoreTimeoutError NSPersistentStoreIncompatibleVersionHashError
= = = = = = = = = =
134000, 134010, 134020, 134030, 134040, 134050, 134070, 134080, 134090, 134100,
Constants
NSPersistentStoreInvalidTypeError
Error code to denote an unknown persistent store type/format/version. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSPersistentStoreTypeMismatchError
Error code returned by a persistent store coordinator if a store is accessed that does not match the specified type. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
341
NSPersistentStoreIncompatibleSchemaError
Error code to denote that a persistent store returned an error for a save operation. This code pertains to database level errors such as a missing table. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSPersistentStoreSaveError
Error code to denote that a persistent store returned an error for a save operation. This code pertains to errors such as permissions problems. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSPersistentStoreIncompleteSaveError
Error code to denote that one or more of the stores returned an error during a save operations. The stores or objects that failed are in the corresponding user info dictionary of the NSError object. Available in OS X v10.4 and later. Declared in CoreDataErrors.h.
NSPersistentStoreSaveConflictsError
Error code to denote that an unresolved merge conflict was encountered during a save. . The NSError objects user info dictionary contains the key NSPersistentStoreSaveConflictsErrorKey (page 337). Available in OS X v10.7 and later. Declared in CoreDataErrors.h.
NSPersistentStoreOperationError
Error code to denote that a persistent store operation failed. Available in OS X v10.5 and later. Declared in CoreDataErrors.h.
NSPersistentStoreOpenError
Error code to denote an error occurred while attempting to open a persistent store. Available in OS X v10.5 and later. Declared in CoreDataErrors.h.
NSPersistentStoreTimeoutError
Error code to denote that Core Data failed to connect to a persistent store within the time specified by NSPersistentStoreTimeoutOption. Available in OS X v10.5 and later. Declared in CoreDataErrors.h.
342
NSPersistentStoreUnsupportedRequestTypeError
Error code to denote that an NSPersistentStore subclass was passed a request (an instance of NSPersistentStoreRequest) that it did not understand. Available in OS X v10.7 and later. Declared in CoreDataErrors.h.
NSPersistentStoreIncompatibleVersionHashError
Error code to denote that entity version hashes in the store are incompatible with the current managed object model. Available in OS X v10.5 and later. Declared in CoreDataErrors.h.
= = = = = = = = =
Constants
NSMigrationError
Error code to denote a general migration error. Available in OS X v10.5 and later. Declared in CoreDataErrors.h.
NSMigrationCancelledError
Error code to denote that migration failed due to manual cancellation. Available in OS X v10.5 and later. Declared in CoreDataErrors.h.
NSMigrationMissingSourceModelError
Error code to denote that migration failed due to a missing source data model. Available in OS X v10.5 and later. Declared in CoreDataErrors.h.
343
NSMigrationMissingMappingModelError
Error code to denote that migration failed due to a missing mapping model. Available in OS X v10.5 and later. Declared in CoreDataErrors.h.
NSMigrationManagerSourceStoreError
Error code to denote that migration failed due to a problem with the source data store. Available in OS X v10.5 and later. Declared in CoreDataErrors.h.
NSMigrationManagerDestinationStoreError
Error code to denote that migration failed due to a problem with the destination data store. Available in OS X v10.5 and later. Declared in CoreDataErrors.h.
NSEntityMigrationPolicyError
Error code to denote that migration failed during processing of an entity migration policy. Available in OS X v10.5 and later. Declared in CoreDataErrors.h.
NSInferredMappingModelError
Error code to denote a problem with the creation of an inferred mapping model. Available in OS X v10.6 and later. Declared in CoreDataErrors.h.
NSExternalRecordImportError
Error code to denote a general error encountered while importing external records. Available in OS X v10.6 and later. Declared in CoreDataErrors.h.
NSCoreDataError NSSQLiteError
= 134060, = 134180,
344
Constants
NSCoreDataError
Error code to denote a general Core Data error. Available in OS X v10.5 and later. Declared in CoreDataErrors.h.
NSSQLiteError
Error code to denote a general SQLite error. Available in OS X v10.5 and later. Declared in CoreDataErrors.h.
double NSCoreDataVersionNumber;
Constants
NSCoreDataVersionNumber
Specifies the version of Core Data available in the current process. Available in OS X v10.4 and later. Declared in CoreDataDefines.h. Discussion See Core Data Version Numbers (page 345) for defined versions.
#define #define #define #define #define #define #define #define #define #define #define
NSCoreDataVersionNumber10_4 NSCoreDataVersionNumber10_4_3 NSCoreDataVersionNumber10_5 NSCoreDataVersionNumber10_5_3 NSCoreDataVersionNumber10_6 NSCoreDataVersionNumber10_6_2 NSCoreDataVersionNumber10_6_3 NSCoreDataVersionNumber_iOS_3_0 NSCoreDataVersionNumber_iOS_3_1 NSCoreDataVersionNumber_iOS_3_2 NSCoreDataVersionNumber_iPhoneOS_4_0
46.0 77.0 185.0 186.0 246.0 250.0 251.0 241.0 248.0 310.2 320.5
345
320.11 320.15
Constants
NSCoreDataVersionNumber10_4
Specifies the Core Data version number released with OS X v10.4.0. Available in OS X v10.5 and later. Declared in CoreDataDefines.h.
NSCoreDataVersionNumber10_4_3
Specifies the Core Data version number released with OS X v10.4.3. Available in OS X v10.5 and later. Declared in CoreDataDefines.h.
NSCoreDataVersionNumber10_5
Specifies the Core Data version number released with OS X v10.5.0. Available in OS X v10.6 and later. Declared in CoreDataDefines.h.
NSCoreDataVersionNumber10_5_3
Specifies the Core Data version number released with OS X v10.5.3. Available in OS X v10.6 and later. Declared in CoreDataDefines.h.
NSCoreDataVersionNumber10_6
Specifies the Core Data version number released with OS X v10.6.0. Available in OS X v10.7 and later. Declared in CoreDataDefines.h.
NSCoreDataVersionNumber10_6_2
Specifies the Core Data version number released with OS X v10.6.2. Available in OS X v10.7 and later. Declared in CoreDataDefines.h.
NSCoreDataVersionNumber10_6_3
Specifies the Core Data version number released with OS X v10.6.3. Available in OS X v10.7 and later. Declared in CoreDataDefines.h.
NSCoreDataVersionNumber_iOS_3_0
Specifies the Core Data version number released with iOS v3.0.
NSCoreDataVersionNumber_iOS_3_1
Specifies the Core Data version number released with iOS v3.1.
346
NSCoreDataVersionNumber_iOS_3_2
Specifies the Core Data version number released with iOS v3.2.
NSCoreDataVersionNumber_iPhoneOS_4_0
Specifies the Core Data version number released with iOS v4.0. Available in OS X v10.7 and later. Declared in CoreDataDefines.h.
NSCoreDataVersionNumber_iPhoneOS_4_1
Specifies the Core Data version number released with iOS v4.1. Available in OS X v10.7 and later. Declared in CoreDataDefines.h.
NSCoreDataVersionNumber_iPhoneOS_4_2
Specifies the Core Data version number released with iOS v4.2. Available in OS X v10.7 and later. Declared in CoreDataDefines.h. Discussion See Core Data Version Number (page 345) for the current version.
347
Notes Updated for OS X v10.7. First release for iOS. Updated for OS X v10.6. Updated for OS X v10.5. First publication of this content as a collection of separate documents.
348
Apple Inc. 2004, 2011 Apple Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer for personal use only and to print copies of documentation for personal use provided that the documentation contains Apples copyright notice. No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the technology described in this document. This document is intended to assist application developers to develop applications only for Apple-labeled computers. Apple Inc. 1 Infinite Loop Cupertino, CA 95014 408-996-1010 Apple, the Apple logo, Cocoa, iPhone, iTunes, Mac, Numbers, Objective-C, OS X, Spotlight, and Xcode are trademarks of Apple Inc., registered in the U.S. and other countries. Times is a registered trademark of Heidelberger Druckmaschinen AG, available from Linotype Library GmbH. iOS is a trademark or registered trademark of Cisco in the U.S. and other countries and is used under license.
Even though Apple has reviewed this document, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS DOCUMENT IS PROVIDED AS IS, AND YOU, THE READER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY. IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages. THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make any modification, extension, or addition to this warranty. Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state.