I am interested in a terse way to do a lookup for a match within an array that requires levels of sub-objects. The performance does not have to be close to ideal but should be reasonable.
For this case I do not want to add a reverse relationship or manage retained dictionaries . I don't want to change the model at all.
Object1 contains an Object2, and Object2 contains an Object3. I understand that the following method will return the first match, however a solution that returns every match would also be acceptable.
-(Object1*)getObject1ForObject3:(Object3*)object3
{
for(Object1 *object1 in self.object1s)
if(object1.object2.object3 == object3)
return object1 ;
return nil ;
}
And for prestige, can we make it terse if there is a to-many relationship in the middle?
-(Object1*)getObject1ForObject3:(Object3*)object3
{
for(Object1 *object1 in self.object1s)
for(Object2 *object2 in object1.object2s)
if(object2.object3 == object3)
return object1 ;
return nil ;
}
Well, the API for declaring an NSPredicate isn't exactly terse , but it's still probably more terse than what you're doing.
For the first case, where there's not a to-many in the middle:
NSPredicate *pred = [NSPredicate predicateWithFormat:@"object2.object3 == %@", object3];
NSArray *matchingObj1s = [self.object1s filteredArrayUsingPredicate];
When there's a to-many relationship in the middle:
NSPredicate *pred = [NSPredicate predicateWithFormat:@"ANY object2s.object3 == %@", object3];
NSArray *matchingObj1s = [self.object1s filteredArrayUsingPredicate];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.