をここでは、このようなあなたのネストされたオブジェクトにアクセスできるように、配列のインデックスを処理することができ、私は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"];
のようにそれを使用しますので、それはしやすいですあなたはアイデアを得る。私はこの回答を、同様の(リンクされた)質問に投稿しました。
出典
2012-12-11 21:12:49
psy
答えは "いいえ"のように見えます:[値の配列の要素を取得する](http://stackoverflow.com/questions/1461126/getting-array-elements-with-valueforkeypath) –