在调用NSDictionary valueForKeyPath时,如果路径的一个级别是一个数组,你可以指定数组中的特定元素吗?
例如:
[myDict valueForKeypath:@"customer.contactInfo.phoneNumbers[4].countryCode];
其中.phoneNumbers是NSArray。或者我必须:
NSArray *numbers=[myDict valueForKeypath:@"customer.contactInfo.phoneNumbers];
NSString *countryCode=[[numbers objectAtIndex:4] objectForKey:@"countryCode"];
如果可以在一个声明中完成,那将是非常好的和更清洁。
答案 0 :(得分:1)
你可以这样做:
NSString *myString = [[[myDict valueForKeypath:@"customer.contactInfo.phoneNumbers"] objectAtIndex:4] objectForKey:@"countryCode"];
答案 1 :(得分: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"];
没有错误检查,所以它很容易破坏,但你明白了。我把这个答案发给了一个类似的(链接的)问题。