William Jockusch
William Jockusch

Reputation: 27335

Restoring a BOOL inside an NSDictionary from a plist file

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.

Upvotes: 38

Views: 21862

Answers (3)

Daniil Chuiko
Daniil Chuiko

Reputation: 876

It's possible to use new format:

Bool isMale = [dictionary[@"isMale"] boolValue]

Upvotes: 1

djdrzzy
djdrzzy

Reputation: 613

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.

Upvotes: 6

Vladimir
Vladimir

Reputation: 170849

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

Upvotes: 95

Related Questions