Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Tuesday, December 17, 2013

iOS Get Bool from NSDictionary

So, you want to fetch and store a Boolean in an NSDictionary, huh?

NSDictionary objects are so awesome and useful. However, one thing that may not seem obvious at first is that NSDictionaries cannot store what are considered primitive types: int, float, double, as well as the scalar BOOL data-type. However, they can store objects like crazy. Most of the time, if we want to store a BOOL YES/NO value in an NSDictionary, we'll use NSNumber as an intermediary data-type like so:

  NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
  [dictionary setObject:[NSNumber numberWithBool:YES] forKey:@"myBooleanValue"];

Then, to fetch it back out again, and for the sake of explicitness, we can do this to get the value that we stored in the dictionary in the form of a BOOL:

  BOOL *myBooleanValue = [(NSNumber *)[dictionary objectForKey:@"myBooleanValue"] boolValue];

You may choose any intermediary type you'd like, but NSNumber is efficient and commonly used in this situation, so its recommended that you use this approach.

Best of luck on your journey.

About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates:

Popular Posts

Designed By Seo Blogger Templates