Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Photo Browser iPhone App Connecting to an API using OAuth Caching Photos

protection against a Null Dictionary Object

I ran into a null dictionary object earlier today and it crashed my app. In order to protect against this, I've modified my setPhoto method to the following.

  • (void)setPhoto:(NSDictionary *)photo { _photo = photo;

    if ([photo isKindOfClass:[NSDictionary class]]){ NSURL *url = [[NSURL alloc] initWithString:_photo[@"images"][@"standard_resolution"][@"url"]]; [self downloadPhotoWithURL:url]; }else{ NSLog(@"Null Object"); } } The isKindOfClass checks to see if a dictionary object is being passed, since if a property is NULL it will cause an error reading [NSNULL objectForKey] sent to instance xxxxxxxxx invalid selector.

1 Answer

Sam Soffes
STAFF
Sam Soffes
Treehouse Guest Teacher

That works. I generally do something like object == [NSNull null] insteadโ€”although yours is definitely safer. In the Photo Bombers app, you shouldn't be inserting null into your data anywhere though. I'd do checks where you're inserting to be sure you only insert good data.

For iOS apps, it's generally a good practice to optimize for reading over writing.