Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.