This is my core data model:
I have two Entities: Folder <->> Note
and I want to fetch all the notes in a folder.
This is my core data model:
I have two Entities: Folder <->> Note
and I want to fetch all the notes in a folder.
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)
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
{
....
}
}