NSArray的-valueForKey问题:当它的项目是NSDictionary时

时间:2012-02-05 02:54:04

标签: objective-c kvc

我有一个包含NSDictionary项的数组,我想将项目转换为其他对象,我的第一个想法是valueForKey:,所以我为{添加了一个类别方法toMyObject {1}},并致电:

NSDictionary

但它没有按预期工作,它只返回[array valueForKey:@"toMyObject"] s。

的数组

如果我不想枚举数组,有什么想法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

回答我自己。字典的valueForKey:会覆盖默认行为,如果字典没有密钥,它将返回nil,而不是像NSObject那样调用访问器方法,正如Apple文档所说:

  

如果key不以“@”开头,则调用objectForKey:。如果关键   以“@”开头,剥离“@”并调用[super valueForKey:]   关键的其余部分。

由于NSDictionary是一个集群类,因此不建议使用子类来覆盖该行为。相反,我使用瑞士这样的方法:

@implementation NSDictionary (MyAddition)

static void swizzle(Class c, SEL orig, SEL new)
{
  Method origMethod = class_getInstanceMethod(c, orig);
  Method newMethod = class_getInstanceMethod(c, new);
  if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
    class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
  else
    method_exchangeImplementations(origMethod, newMethod);
}

+ (void)initialize
{
  if (self == [NSDictionary class]){
    swizzle([NSDictionary class],
            @selector(valueForKey:),
            @selector(myValueForKey:));
  }
}

- (id)toMyObject
{
  return toMyObject;
}

...

- (id)myValueForKey:(NSString *)key
{
  // for collection operators
  if ([key compare:@"@" options:0 range:NSMakeRange(0, 1)] == NSOrderedSame)
    return [super valueForKey:key];

  if ([key isEqualToString:@"toMyObject"])
    return [self toMyObject];

  return [self myValueForKey:key];
}

现在,NSArray可以安全地拨打valueForKey:@"toMyObject"

答案 1 :(得分:0)

还有一个没有调整的实现:

@implementation NSObject (MLWValueForKey)

- (id)mlw_valueForKey:(NSString *)key {
    if ([key hasPrefix:@"@"]) {
        return [self valueForKey:key];
    }
    NSAssert(![key containsString:@":"], @"Key should be selector without arguments");
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    return [self performSelector:NSSelectorFromString(key)];
#pragma clang diagnostic pop
}

@end

@implementation NSArray (MLWValueForKey)

- (id)mlw_valueForKey:(NSString *)key {
    if ([key hasPrefix:@"@"]) {
        return [self valueForKey:key];
    }
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.count];
    for (id object in self) {
        [array addObject:[object mlw_valueForKey:key]];
    }
    return array;
}

@end