Keypath for first element in embedded NSArray

这一生的挚爱 提交于 2019-11-29 01:52:40

Well to answer my own question, one way to do it is this:

1) Define the following category

@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) Use this KeyPath syntax

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

Thanks to this clever person.

@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”];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!