Class: NSManagedObjectContext

Inherits:
NSObject show all

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.

Instance Method Summary (collapse)

Methods inherited from NSObject

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

Constructor Details

This class inherits a constructor from NSObject

Dynamic Method Handling

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

Instance Method Details

- (Object) assignObject(object, toPersistentStore:store)

Specifies the store in which a newly-inserted object will be saved. You can obtain a store from the persistent store coordinator, using for example persistentStoreForURL:.

Parameters:

Returns:

- (NSManagedObjectContextConcurrencyType) concurrencyType

Returns the concurrency type for the receiver.

Returns:

  • (NSManagedObjectContextConcurrencyType)

    The concurrency type for the receiver.

- (Integer) countForFetchRequest(request, error:error)

Returns the number of objects a given fetch request would have returned if it had been passed to executeFetchRequest:error:.

Parameters:

  • request (NSFetchRequest)

    A fetch request that specifies the search criteria for the fetch.

  • error (Pointer)

    If there is a problem executing the fetch, upon return contains an instance of NSError that describes the problem.

Returns:

  • (Integer)

    The number of objects a given fetch request would have returned if it had been passed to executeFetchRequest:error:, or NSNotFound if an error occurs.

- (NSSet) deletedObjects

Returns the set of objects that will be removed from their persistent store during the next save operation. The returned set does not necessarily include all the objects that have been deleted (using deleteObject:)—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 notification when a change is made, and a NSManagedObjectContextWillSaveNotification notification and a NSManagedObjectContextDidSaveNotification notification before and after changes are committed respectively (although again the set of deleted objects given for a NSManagedObjectContextDidSaveNotification does not include objects that were inserted and deleted without an intervening save operation—that is, they had never been saved to a persistent store).

Returns:

  • (NSSet)

    The set of objects that will be removed from their persistent store during the next save operation.

- (Object) deleteObject(object)

Specifies an object that should be removed from its persistent store when changes are committed. 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.

Parameters:

Returns:

- (Object) detectConflictsForObject(object)

Marks an object for conflict detection. If on the next invocation of save: 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.

Parameters:

Returns:

- (Array) executeFetchRequest(request, error:error)

Returns an array of objects that meet the criteria specified by a given fetch request. 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 request’s 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 request’s 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. 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 objects—you get the existing objects with their current in-memory state.

Parameters:

  • request (NSFetchRequest)

    A fetch request that specifies the search criteria for the fetch.

  • error (Pointer)

    If there is a problem executing the fetch, upon return contains an instance of NSError that describes the problem.

Returns:

  • (Array)

    An array of objects that meet the criteria specified by request fetched from the receiver and from the persistent stores associated with the receiver’s persistent store coordinator. If an error occurs, returns nil. If no objects match the criteria specified by request, returns an empty array.

- (NSManagedObject) existingObjectWithID(objectID, error:error)

Returns the object for the specified ID. 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:, this method never returns a fault.

Parameters:

  • objectID (NSManagedObjectID)

    The object ID for the requested object.

  • error (Pointer)

    If there is a problem in retrieving the object specified by objectID, upon return contains an error that describes the problem.

Returns:

  • (NSManagedObject)

    The object specified by objectID. If the object cannot be fetched, or does not exist, or cannot be faulted, it returns nil.

- (Boolean) hasChanges

Returns a Boolean value that indicates whether the receiver has uncommitted changes. In OS X v10.6 and later, this property is key-value observing compliant.

Returns:

  • (Boolean)

    YES if the receiver has uncommitted changes, otherwise NO.

- (Object) initWithConcurrencyType(ct)

Initializes a context with a given concurrency type.

Parameters:

  • ct (NSManagedObjectContextConcurrencyType)

    The concurrency pattern with which context will be used.

Returns:

  • (Object)

    A context initialized to use the given concurrency type.

- (NSSet) insertedObjects

Returns the set of objects that have been inserted into the receiver but not yet saved in a persistent store. A managed object context does not post key-value observing notifications when the return value of insertedObjects changes—it does, however, post a NSManagedObjectContextObjectsDidChangeNotification notification when a change is made, and a NSManagedObjectContextWillSaveNotification and a NSManagedObjectContextDidSaveNotification notification before and after changes are committed respectively.

Returns:

  • (NSSet)

    The set of objects that have been inserted into the receiver but not yet saved in a persistent store.

- (Object) insertObject(object)

Registers an object to be inserted in the receiver’s persistent store the next time changes are saved. 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 message) before a save operation, the object is unregistered from the receiver.

Parameters:

Returns:

- (Object) lock

Attempts to acquire a lock on the receiver. This method blocks a thread’s 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.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 NSManagedObjectContext’s 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.

Returns:

- (Object) mergeChangesFromContextDidSaveNotification(notification)

Merges the changes specified in a given notification.

This method refreshes any objects which have been updated in the other context, faults in any newly-inserted objects, and invokes deleteObject

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

Parameters:

  • notification (NSNotification)

    An instance of an NSManagedObjectContextDidSaveNotification notification posted by another context.

Returns:

- (Object) mergePolicy

Returns the merge policy of the receiver. The default is NSErrorMergePolicy.

Returns:

  • (Object)

    The receiver’s merge policy.

- (NSManagedObject) objectRegisteredForID(objectID)

Returns the object for a specified ID, if the object is registered with the receiver.

Parameters:

Returns:

  • (NSManagedObject)

    The object for the specified ID if it is registered with the receiver, otherwise nil.

- (NSManagedObject) objectWithID(objectID)

Returns the object for a specified ID. 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 exist—if 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.

Parameters:

Returns:

- (Boolean) obtainPermanentIDsForObjects(objects, error:error)

Converts to permanent IDs the object IDs of the objects in a given array. 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 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).

Parameters:

  • objects (Array)

    An array of managed objects.

  • error (Pointer)

    If an error occurs, upon return contains an NSError object that describes the problem.

Returns:

  • (Boolean)

    YES if permanent IDs are obtained for all the objects in objects, otherwise NO.

- (NSManagedObjectContext) parentContext

Returns the receiver’s parent context.

Returns:

- (Object) performBlock

Parameters:

  • block (Object)

    The block to perform.

Returns: