ios - Core data filtering -
i have core data structure follows:
business <-------->> employee <-------->> address
each business has multiple employees , each employee can have multiple addresses.
from business object, want able nsarray
or nsset
of address
objects specify condition. e.g. street names have unique.
i know override isequal:
i'm guessing going have unintended results. otherwise, have been looking using valueforkeypath:@"@distinctunionofobjects"
, don't think can pass condition.
here code have far:
nsmutablearray *addressarray = [nsmutablearray array]; nsarray *employees = [employee sortedarray]; //loop through employees (employee *employee in employees) { (address *address in employee.addresses) { [addressarray addobject:address]; } } //filter out duplicates addressarray = [addressarray valueforkeypath:@"@distinctunionofobjects.city"];
this code gives me list of unique cities, however, want collection containing address
objects have unique city
values (or other condition).
i found way linqtoobjectivec library:
nsarray* addresseswithuniquecities = [input distinct:^id(id address) { return [address city]; }];
looking @ source, underlying implementation follows:
typedef id (^selector)(id item); -(nsarray *)distinct:(selector)keyselector { nsmutableset* keyvalues = [[nsmutableset alloc] init]; nsmutablearray* distinctset = [[nsmutablearray alloc] init]; (id item in self) { id keyforitem = keyselector(item); if (![keyvalues containsobject:keyforitem]) { [distinctset addobject:item]; [keyvalues addobject:keyforitem]; } } return distinctset; }
my final code ended being:
nsmutablearray *addressarray = [nsmutablearray array]; nsarray *employees = [employee sortedemployees]; //loop through employees (employee *employee in employees) { (address *address in employee.addresses) { [addressarray addobject:address]; } } //filter out duplicates nsarray *distinctaddressarray = [addressarray distinct:^id(id address) { return [address addressline]; }]; return distinctaddressarray;
Comments
Post a Comment