iosswiftcore-datanspredicate

How to create predicate to search core data entities with property for selected entity of one to many relationship?


Simply I have two Entities: Address and Note. Address has many notes assigned. Every Note has text and date properties.

@objc(Address)
class Address: NSManagedObject {
    @NSManaged var identifier: String
    @NSManaged var notes: Set<Note>
}

@objc(Note)
class Note: NSManagedObject {
    @NSManaged var identifier: String
    @NSManaged var text: String
    @NSManaged var date: Date
    @NSManaged var address: Address
}

let phrase = "some search text"

Every address may have from 0 to many notes sorted by date.

I know how to do it when ANY of the notes contains phrase:

let predicate = NSPredicate(format: "ANY notes.text CONTAINS [cd] %@", phrase)

But now I need NSPredicate to query all addresses where text in last note contains phrase.


Solution

  • If you say "last note", you mean the one that has the most recent date?

    Set<Note> is an unordered collection, so you cannot simply access one item without querying for all and get the one with the latest date. That would work by using a SUBQUERY. But this is not really recommended if you have large datasets because it will be slow.

    In case you frequently need to fetch those Address objects where the last note contains a certain text, it would be smarter to add that text of the last note as property of the address itself instead and update it whenever necessary. Or also, a 1:1 relationship for the last note if you need more of its properties.