4

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.

andrewtweber
  • 24,520
  • 22
  • 88
  • 110

2 Answers2

13

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)
vadian
  • 274,689
  • 30
  • 353
  • 361
2

Write these line of code in your func

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 
{
....
}

}
Tbaki
  • 1,013
  • 7
  • 12