Difference Between objectForKey and valueForKey in NSDictionary

1,一般情况下,两者是 一样的,valueforkey == objectforkey

2,当 key是 以@开头的时候 ,如下:

 NSDictionary *dict = [NSDictionary dictionaryWithObject:@"theValue" forKey:@"@theKey"];// 注意这个 key 是以 @ 开头

NSString *value1 = [dict objectForKey:@"@theKey"];

NSString *value2 = [dict valueForKey:@"@theKey"];

这个时候,valueforkey就会 报错, [dict valueForKey:@"@theKey"]; 会把 key 里的 @ 去掉,也就变成了 [dict valueForKey:@"theKey"];,而 dict 不存在 theKey 这样的 property,转而执行 [dict valueForUndefinedKey:@"theKey"];,抛出 NSUndefinedKeyException 异常后 crash 掉。为什么 会去掉呢,鬼才知道呢,

3,这个方法是 防止 返回 null情况的,

- (id)valueForKeyNullReplace:(NSString *)key

{

    id value = [self valueForKey:key];

    if ([value isKindOfClass:[NSNull class]]) {

        return nil;

    }

    return value;

}

4,在value - key 的情况下,@""是被解析为nil么,?

原文地址:https://www.cnblogs.com/guligei/p/3333013.html