Reputation: 3674
In my project, I have two entities: personEntity
& municipalEntity
. These have a many-to-many inverse relationship with each other. I execute a NSFetchRequest
on personEntity
to get a person's details:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDelegate.managedObjectContext
let personRequest = NSFetchRequest(entityName: "personEntity")
let personPred = NSPredicate(format: "surname = %@", "Smith")
personRequest.predicate = personPred
do {
let personsList = try context.executeFetchRequest(personRequest)
// this all clear enough up to this point
At this point, I try to nest a second, predicated FetchRequest
within the first. This request should search municipalEntity
in its peopleInMunicipality
relationship property, for the objects from personsList
.
for selectedPeople in personsList {
let municipalRequest = NSFetchRequest(entityName: "municipalEntity")
let municipalPred = NSPredicate(format: "peopleInMunicipality = %@", selectedPeople)
municipalRequest.predicate = municipalPred
do {
let municipalitiesWithResidentsCalledSmithList = try context.executeFetchRequest(municipalRequest)
And bang... the compiler complains and suggests I need to change two things in the line defining the second predicate. It suggests instead...
let municipalPred = NSPredicate(format: "peopleInMunicipality = %@", argumentArray: selectedPerson as? [AnyOject])
The compiler is now happy but when I run the code, it crashes with an EXC_BAD_ACCESS error on the suggested argumentArray:
code section.
Any idea how I can fix this?
Upvotes: 0
Views: 106
Reputation: 1960
Since I cannot post comment. You can try SubQuery on MunicipalEntity like this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SUBQUERY(peopleInMunicipality, $person, $person.surname == %@).@count > 0", @"Smith"];
Use this Predicate on Municipal Entity
Upvotes: 0
Reputation: 15598
vadian is right. You don't need the second fetch request. If the reverse relationship of peopleInMunicipality
is called municipalities
, the municipalities of selectedPeople
is selectedPeople.municipalities
.
If you really want to execute a second fetch request, the predicate format would be peopleInMunicipality CONTAINS %@
.
Upvotes: 1