> On Nov 10, 2015, at 8:32 AM, Alex Zavatone <z...@mac.com> wrote:
> 
> It's been about 4 or 5 years since I made this mistake but I've just seen a 
> massive swath of code where every access of a dictionary object is using 
> valueForKey instead of objectForKey.
> 
> I've got a few examples of why this is a "really bad idea"™, and certainly 
> might explain why lots of that code is wrapped in try/catch blocks.
> 
> Am I correct that using valueForKey will raise an exception if the key is 
> missing?
> 
> Looking for reasons why I can explain "yeah, I know it works, but here's why 
> it's a terrible idea to use to access a dictionary's objects".

-valueForKey: interprets keys whose name starts with '@' specially. Examples:

[dict valueForKey:@"@allKeys"] returns an array of all keys in the dictionary.

valueForKey: throws an exception if the key name starts with '@' and the name 
isn't recognized by KVC as special.


% cat test.m
#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    NSDictionary *dict = @{ @"ordinary" : @"ordinary value", 
                            @"@allKeys" : @"@allKeys value", 
                            @"something" : @"something value", 
                            @"@something" : @"@something value" };

    // -objectForKey does the usual thing
    NSLog(@"-- objectForKey --");
    NSLog(@"%@", [dict objectForKey:@"ordinary"]);
    NSLog(@"%@", [dict objectForKey:@"@allKeys"]);
    NSLog(@"%@", [dict objectForKey:@"@something"]);

    // -valueForKey does not
    NSLog(@"-- valueForKey --");
    NSLog(@"%@", [dict valueForKey:@"ordinary"]);
    NSLog(@"%@", [dict valueForKey:@"@allKeys"]);
    NSLog(@"%@", [dict valueForKey:@"@something"]);
}

% clang test.m -framework Foundation && ./a.out
2015-11-10 10:00:55.295 a.out[38293:4747164] -- objectForKey --
2015-11-10 10:00:55.296 a.out[38293:4747164] ordinary value
2015-11-10 10:00:55.296 a.out[38293:4747164] @allKeys value
2015-11-10 10:00:55.296 a.out[38293:4747164] @something value
2015-11-10 10:00:55.296 a.out[38293:4747164] -- valueForKey --
2015-11-10 10:00:55.296 a.out[38293:4747164] ordinary value
2015-11-10 10:00:55.297 a.out[38293:4747164] (
    something,
    ordinary,
    "@allKeys",
    "@something"
)
2015-11-10 10:00:55.298 a.out[38293:4747164] *** Terminating app due to 
uncaught exception 'NSUnknownKeyException', reason: '[<__NSDictionaryI 
0x7fc0b850ead0> valueForUndefinedKey:]: this class is not key value 
coding-compliant for the key something.'


-- 
Greg Parker     gpar...@apple.com     Runtime Wrangler



_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to