Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

objective c - Keypath for first element in embedded NSArray

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

(This is an NSArray containing NSDictionarys that have an object of type NSArray).

The key field is work. I want a Key Path that will take the first object in the work array.

If I do this:

NSArray* work = [outerArrayObject objectForKey: @"work"];
id name = [work valueForKeyPath: @"employer.name"];

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@PauldeLange - Your answer and links were helpful.
The following simpler version works too (at least as of Xcode 6)

id name = [work valueForKeyPath: @"employer.name.@firstObject”];

In the above 'firstObject' refers to the predefined method on NSArray. If the second object is needed, you can define the following:

@implementation NSArray (CustomKVOOperators)

- (id) secondObject {
    return [self count] >=2 ? self[1] : nil;
}
@end

And use:

 id name = [work valueForKeyPath: @"employer.name.@secondObject”];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...