2012-02-16 21 views
1

パスの1つのレベルが配列の場合、NSDictionary valueForKeyPathを呼び出す際に、配列内の特定の要素を指定できますか?例えばvalueForKeyPathステートメントで特定のオブジェクトインデックスを指定する方法はありますか?

:.phoneNumbersはNSArrayのある

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

。これは1つのステートメントで行うことができれば、それは本当に素晴らしく、非常にクリーンになり

​​

:または私はする必要がありますか。

+0

答えは "いいえ"のように見えます:[値の配列の要素を取得する](http://stackoverflow.com/questions/1461126/getting-array-elements-with-valueforkeypath) –

答えて

1

あなたがこれを行うことができます:

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

これは1つのステートメントです配列要素に直接アクセスするより冗長です。 – ChrisP

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"]; 

のようにそれを使用しますので、それはしやすいですあなたはアイデアを得る。私はこの回答を、同様の(リンクされた)質問に投稿しました。

関連する問題