How can I get relationships in Core Data swift
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 to share
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 to share