views:

69

answers:

2

I have a plist file which contains an array of dictionaries. Here is one of them:

Fred Dictionary
Name Fred
isMale [box is checked]

So now I am initializing my Person object with the dictionary I read from the plist file:

 -(id) initWithDictionary: (NSDictionary *) dictionary {
    if (self = [super init])
    self.name = [dictionary valueForKey: @"Name"];
    self.isMale = ????
  }

How do I finish off the above code so that self.isMale is set to YES if the box is checked in the plist file, and NO if it isn't. Preferably also set to NO if there is no key isMale in the dictionary.

+4  A: 

BOOL values usually stored in obj-c containers wrapped in NSNumber object. If it is so in your case then you can retrieve bool value using:

self.isMale = [[dictionary objectForKey:@"isMale"] boolValue];
Vladimir
A: 

Vladimir is right, I'm just going to chime in and say it is good to check that those values from the plist exist as well, and if not set it to a default value usually.

Something like:

id isMale = [dictionary valueForKey:@"isMale"];
self.isMale = isMale ? [isMale boolValue] : NO;

Which checks to see if the value for the key "isMale" exists in the dictionary. If it does then it gets the boolValue from it. If it does not then it sets self.isMale to the default of NO.

djdrzzy
That's only necessary if you want the person to be male by default (default to `YES`). You can send the message to `nil` (the return value of `-[NSDictionary objectForKey:]` and `-[NSDictionary valueForKey:]` when the key is not present in the dictionary) without checking first if you're OK with a default of `NO`. http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocObjectsClasses.html%23//apple_ref/doc/uid/TP30001163-CH11-SW7
Peter Hosey
Ah yeah you're right. I got caught in between trying to provide a general answer for values other than BOOL (such as a NSString) and providing a general way to provide default values.
djdrzzy
I'm going to be a jerk and say that Apple isn't guaranteed to keep NO defined to (BOOL)0 forever though in which case the default value might not be always NO. :P If they ever changed it though that'd be pretty stupid and impractical.
djdrzzy
Not least because then it wouldn't work with the C `if` statement, which tests whether the condition expression is not 0. ☺
Peter Hosey