Using NSDelegate delegates filtering to Core Data which can be more efficient, especially on large data sets.
A description of search criteria used to retrieve data from a persistent store.
Project: Chott for iOS According to this Stack Overflow answer, the UUID will be stored as a binary when that entity is saved with Core Data, which is more optimal than using strings for storage. This can be used to give your data objects a unique identity when needed.
You want:
-(NSManagedObject *)existingObjectWithID:(NSManagedObjectID *)objectID
error:(NSError **)error
Fetches the object from the store that has that ID, or nil if it doesn't exist.
(Be aware: there are two methods on NSManagedObjectContext with similar-seeming names that tripped me up. To help keep them straight, here's what the other two do:
-(NSManagedObject *)objectWithID:(NSManagedObjectID *)objectID
...will create a fault object with the provided objectID, whether or not such an object actually exists in the store. If it doesn't exist, anything that fires the fault will fail unless you insert the object first with NSManagedObjectContext's insertObject:
. The only use I've found for this is copying objects from store to store while preserving ObjectIDs.
-(NSManagedObject *)objectRegisteredForID:(NSManagedObjectID *)objectID
...will return the object that has that ID, if it has been fetched from the store by this managedObjectContext. If anyone knows what this method is useful for, please comment.)
[eta.: Another important difference between the first method and the other two is that existingObjectWithID:error:
never returns a fault; it always fetches the whole object for you. If you're trying to avoid that (e.g. working with an expensive-to-fetch object with a big blob property), you have to be clever with objectWithID:
or objectRegisteredForID:
, which don't fire faults; or use a properly configured fetch request.]
objectWithID:
is the method you are looking for, and it is the recommended way to do this. objectWithID:
will efficiently use the NSManagedObjectContext to pull the object only as many levels as needed - unlike some of the other means of doing this. objectWithID:
will correctly use in-memory information in parent contexts, the persistent store coordinator, and the persistent store itself before going to the backing storage.
This is covered in depth in the WWDC 2012 session "Core Data Best Practices".
Swift 5 version:
https://developer.apple.com/documentation/coredata/nsmanagedobjectcontext/1506686-existingobject
there are also methods object(with:)
or registeredObject(for:)
. Depending on what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With