Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fetch a relationship in Core Data swift

This is my core data model:

enter image description here

I have two Entities: Folder <->> Note and I want to fetch all the notes in a folder.

like image 947
gabriel igliozzi Avatar asked Dec 07 '22 18:12

gabriel igliozzi


1 Answers

First of all it's recommended to name the many relationship as plural (notes), that makes it easier to understand the model.

If you have a NSManagedObject subclass and a reference to a folder just get the notes by the relationship:

let notes = folder.notes

However this returns a Set. If you want an array write

let notes = folder.notes.allObjects as! [Note]

You can also use a predicate to be assigned to a fetch request on the Note entity:

let name = "Foo"
let predicate = NSPredicate(format:"folder.name == %@", name)
like image 57
vadian Avatar answered Dec 20 '22 08:12

vadian