Question

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.

Was it helpful?

Solution

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];

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top