Restoring a BOOL inside an NSDictionary from a plist file
Asked Answered
D

3

38

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.

Degradation answered 29/9, 2010 at 14:30 Comment(0)
H
95

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];
Hysterectomize answered 29/9, 2010 at 14:34 Comment(0)
S
6

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.

Subaqueous answered 29/9, 2010 at 15:47 Comment(4)
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. developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/…Lionhearted
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.Subaqueous
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.Subaqueous
Not least because then it wouldn't work with the C if statement, which tests whether the condition expression is not 0. ☺Lionhearted
E
1

It's possible to use new format:

Bool isMale = [dictionary[@"isMale"] boolValue]
Edwin answered 26/8, 2021 at 10:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.