How can I get relationships in Core Data swift

This is my main data model:

enter image description here

I have two objects: Folder <->> Note

and I want to get all the notes in a folder.

+3


source to share


2 answers


First of all, it is recommended to name many relations as plural ( notes

), which makes the model easier to understand.

If you have a subclass NSManagedObject

and a folder reference just gets notes in relation to:

let notes = folder.notes

      

However, this returns a Set

. If you want the array to write



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

      

You can also use a predicate that will be assigned to a select query on an object Note

:

let name = "Foo"
let predicate = NSPredicate(format:"folder.name == %@", name)

      

+4


source


Write this line of code in your function



let container = (UIApplication.shared.delegate as! AppDelegate).persistentContainer
        let context: NSManagedObjectContext = container.viewContext
        let request:NSFetchRequest<Notes> = Notes.fetchRequest()


  request.predicate = NSPredicate(format: "here write relationship name .folderName = %@" , searchbar.text!)
        }
        do
        {
            let result = try context.fetch(request)
            for notes in result 
{
....
}

}

      

0


source







All Articles