问题描述
这个例子是人为设计的,但它说明了我的观点.
This example is contrived, but it shows my point.
所以,如果我有一个如下的对象图:
So, if I have an object graph like the following:
{
sex = male;
uid = 637650940;
work = ({
employer = {
id = 116420715044499;
name = "Software Engineer";
};
"end_date" = "0000-00";
"start_date" = "0000-00";
}, {
employer = {
id = 188733137832278;
name = "Apple";
};
});
},
//Some more objects
(这是包含对象类型为NSArray的NSDictionary的NSArray).
(This is an NSArray containing NSDictionarys that have an object of type NSArray).
关键字段是work
.我想要一个键路径,该键路径将使用work
数组中的第一个对象.
The key field is work
. I want a Key Path that will take the first object in the work
array.
如果我这样做:
NSArray* work = [outerArrayObject objectForKey: @"work"];
id name = [work valueForKeyPath: @"employer.name"];
我得到一个包含每个名称的数组(在上述情况下,为Software Engineer&Apple).是否有一个集合运算符或某种可以返回第一个对象的东西?如果您可以开发一个关键路径来按start_date对每个作品进行排序,也可以加分:)
I get an array containing each name (In the above case, Software Engineer & Apple). Is there a collection operator or something to return the first object? Bonus points if you can develop a Key Path to sort each work by start_date also :)
推荐答案
很好地回答我自己的问题,一种解决方法是:
Well to answer my own question, one way to do it is this:
1)定义以下类别
@implementation NSArray (CustomKVOOperators)
- (id) _firstForKeyPath: (NSString*) keyPath {
NSArray* array = [self valueForKeyPath: keyPath];
if( [array respondsToSelector: @selector(objectAtIndex:)] &&
[array respondsToSelector: @selector(count)]) {
if( [array count] )
return [array objectAtIndex: 0];
else
return nil;
}
else {
return nil;
}
}
@end
2)使用此KeyPath语法
2) Use this KeyPath syntax
NSArray* work = [outerArrayObject objectForKey: @"work"];
id name = [work valueForKeyPath: @"@first.employer.name"];
感谢这个聪明的人.
这篇关于嵌入式NSArray中第一个元素的键路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!