[英]How can I make sub-object searching more terse?
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. Object1包含一个Object2,而Object2包含一个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. 嗯,用于声明NSPredicate的API并不十分简洁 ,但它可能比您正在做的还要简洁。
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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.