Trombone0904
Trombone0904

Reputation: 4268

Core Data - fetch object with keypath and Object ID

I would like to fetch my data from Core Data, where the books assigned to the person "Max". For this, I have the following code:

  let request = NSFetchRequest<Book>(entityName: "Book")
    request.predicate = NSPredicate(format: "person.firstName = %@", "Max")
    do {
       let books = try context.fetch(request)
       for x in 0 ..< books.count {
          print(books[x].name)
       }
    } catch { }

But now I would like to fetch the data where the books are assigned to a person with the Object ID "xyz".

I tried this, but it doesn't work:

request.predicate = NSPredicate(format: "person.self = %@", myPersonObjectID)

Upvotes: 0

Views: 1952

Answers (1)

user3151675
user3151675

Reputation: 58149

You should get the object with existingObject from the Object ID and use that in the predicate.

if let myPerson = context.existingObject(with: myPersonObjectID) {
    request.predicate = NSPredicate(format: "person = %@", myPerson)
}

Upvotes: 1

Related Questions