Reputation: 3
My model:
I want to get an array of coutries ONLY with cities, names of which contain given part of the word.
I tried:
let request : NSFetchRequest<Country> = Country.fetchRequest()
request.predicate = NSPredicate(format: "SUBQUERY(cities, $city, $city.name CONTAINS[cd] %@).@count > 0", givenWordPart)
let countries: [Country] = try! context.fetch(request)
But it returns an array of countries with ALL the cities in it.
Upvotes: 0
Views: 53
Reputation: 52013
I think you need to gather your result in two separate collections instead. Create a fetch request for City instead using the same predicate as above but as a normal query instead of a sub-query.
This would return an array of City instances that match your search criteria, to get the selection of countries you could extract them from the cities array
//fetch and predicate declaration...
let cities: [City] = try! context.fetch(request)
let countries = Set<Country>(cities.map({$0.country }))
This assumes you have defined the inverse to-one relationship from City to Country
Upvotes: 0
Reputation: 13296
That is expected behaviour. It queries for Countries
and returns the ones matching the predicate. The returned Countries
still have all their cities and if you want only cities with a specific rule, you'll have to the cities
collection for each Country
Upvotes: 0