Getting array elements with valueForKeyPath

前端 未结 4 1111
眼角桃花
眼角桃花 2020-12-03 05:06

Is there any way to access an NSArray element with valueForKeyPath? Google\'s reverse geocoder service, for example, returns a very complex data s

4条回答
  •  佛祖请我去吃肉
    2020-12-03 05:56

    Here's a category I just wrote for NSObject that can handle array indexes so you can access a nested object like this: "person.friends[0].name"

    @interface NSObject (ValueForKeyPathWithIndexes)
       -(id)valueForKeyPathWithIndexes:(NSString*)fullPath;
    @end
    
    
    #import "NSObject+ValueForKeyPathWithIndexes.h"    
    @implementation NSObject (ValueForKeyPathWithIndexes)
    
    -(id)valueForKeyPathWithIndexes:(NSString*)fullPath
    {
        NSRange testrange = [fullPath rangeOfString:@"["];
        if (testrange.location == NSNotFound)
            return [self valueForKeyPath:fullPath];
    
        NSArray* parts = [fullPath componentsSeparatedByString:@"."];
        id currentObj = self;
        for (NSString* part in parts)
        {
            NSRange range1 = [part rangeOfString:@"["];
            if (range1.location == NSNotFound)          
            {
                currentObj = [currentObj valueForKey:part];
            }
            else
            {
                NSString* arrayKey = [part substringToIndex:range1.location];
                int index = [[[part substringToIndex:part.length-1] substringFromIndex:range1.location+1] intValue];
                currentObj = [[currentObj valueForKey:arrayKey] objectAtIndex:index];
            }
        }
        return currentObj;
    }
    @end
    

    Use it like so

    NSString* personsFriendsName = [obj valueForKeyPathsWithIndexes:@"me.friends[0].name"];
    

    There's no error checking, so it's prone to breaking but you get the idea.

提交回复
热议问题