2012-02-16 67 views
1

在调用NSDictionary valueForKeyPath,如果路径的一个级别是一个数组,你可以在数组中指定一个特定的元素?有没有办法在valueForKeyPath语句中指定特定的对象索引?

例如:

[myDict valueForKeypath:@"customer.contactInfo.phoneNumbers[4].countryCode]; 

其中.phoneNumbers是一个NSArray。还是我来:

​​

这将是非常好的,干净得多,如果这可以在一个语句来完成。

+0

看起来像答案是“否”:[获取数组元素与valueForKeyPath](http://stackoverflow.com/questions/1461126/getting-array-elements-with-valueforkeypath) – 2012-02-16 19:53:35

回答

1

你可以这样做:

NSString *myString = [[[myDict valueForKeypath:@"customer.contactInfo.phoneNumbers"] objectAtIndex:4] objectForKey:@"countryCode"]; 
+0

这是在一个声明,但仍然比直接访问数组元素更详细。 – ChrisP 2012-02-16 20:30:51

0

这里有一个类我写了NSObject的,可以处理数组的索引,以便您可以访问您的嵌套的对象是这样的:“customer.contactInfo.phoneNumbers [4] .countryCode”

@interface NSObject (ValueForKeyPathWithIndexes) 
    -(id)valueForKeyPathWithIndexes:(NSString*)fullPath; 
@end 


#import "NSObject+ValueForKeyPathWithIndexes.h"  
@implementation NSObject (ValueForKeyPathWithIndexes) 

-(id)valueForKeyPathWithIndexes:(NSString*)fullPath 
{ 
    //quickly use standard valueForKeyPath if no arrays are found 
    if ([fullPath rangeOfString:@"["].location == NSNotFound) 
     return [self valueForKeyPath:fullPath]; 

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

使用它像这样

NSString* countryCode = [myDict valueForKeyPathWithIndexes:@"customer.contactInfo.phoneNumbers[4].countryCode"]; 

没有错误校验,所以它容易打破,但你明白了。我交叉发布这个答案的类似(链接)的问题。