2012-02-16 37 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"]; 

沒有錯誤校驗,所以它容易打破,但你明白了。我交叉發佈這個答案的類似(鏈接)的問題。

相關問題