Update: I believe this is duplicate of this: Core Data - Fetch all entities using the same field
I want to use a UUID to find all managed objects that have a property with this ID, regardless of type.
In the typical case, I would use a fetch request on the entity itself. For example, in a Bookstore I could find a book by a bookUUID
using a fetch request on Book
.
class BookShelf: NSManagedObject {
@NSManaged var bookUUID: UUID!
func fetchBook() -> Book? {
let request = Book.fetchRequest()
request.sortDescriptors = []
request.predicate = NSPredicate(format: "%K == %@", "bookUUID", bookUUID as CVarArg)
return try? self.managedObjectContext?.fetch(request).first
}
}
Here this works because BookShelf
knows about Book
. But what about the other way around? When a book deletes itself it should find any entities with a property bookUUID
, regardless of their type.
It could be expressed this way, however this doesn't work. There is no generic NSManagedObject
entity.
extension NSManagedObjectContext {
func findAllObjectsUsingThisBook(bookUUID: UUID) -> Array<NSManagedObject>? {
let request = NSFetchRequest<NSManagedObject>()
request.predicate = NSPredicate(format: "%K == %Q", "bookUUID", uuid as CVarArg)
request.sortDescriptors = []
return try? self.fetch(request)
}
}
Expressed generically, this could be used to find any objects with a certain property.
extension NSManagedObjectContext {
func findAllObjectsWithProperty<T>(named propertyName: String, andValue value: T) -> Array<NSManagedObject>? where T: CVarArg {
let request = NSFetchRequest<NSManagedObject>()
request.predicate = NSPredicate(format: "%K == %Q", propertyName, value)
request.sortDescriptors = []
return try? self.fetch(request)
}
}
How can I accomplish this?