views:

154

answers:

2

Hi,

I'm looking to create a "crash-proof" NSDictionary as I'm using a JSON serializer that converts a server response into an NSDictionary. As as result, sometimes the key for the dictionary is not present. Currently, this will crash the application, however I'd rather an empty NSString was returned so I can display this in the interface.

A solution could be that I check for the key every time I access the dictionary, e.g.

if([returnedDictionary objectForKey:@"key"]){

   // Display [returnedDictionary objectForKey:@"key"];
}else{

   // Display @"";
}

However this soon results in bloated, hard-to-read code.

I had thought about creating a custom NSDictionary object, something like:

@interface NSSafeDictionary : NSDictionary .....

that overrides objectForKey with the above statement.

Is this a satisfactory approach?

Thanks

A: 

Given that it comes in over the network, I would think that you would want to sanitise the data more than just checking for empty values but if not, you don't really need to inherit from NSDictionary.

A simple utility method in your class would do the trick.

Or you could create a category on NSDictionary:

@interface NSDictionary (Safe)

-(NSString*)safeStringForKey:(NSString*)key;

@end

(I'm sure you can figure out the implementation.)

Stephen Darlington
+2  A: 

Are you always going to want to get strings out of your dictionary or will other objects be stored in it as well? If it's only strings, I think the easiest way around this is to construct a category on NSDictionary.

@interface NSDictionary ( EmptyStrings )
- (NSString *)stringForKey:(id)aKey;
@end

@implementation NSDictionary ( EmptyStrings )

- (NSString *)stringForKey:(id)aKey {
    id object = [self objectForKey:aKey];
    if (object == nil ) {
        return @"";
    }
    if ([object isKindOfClass:[NSString class]) {
        return object;
    } else {
        return nil;
    }
}

@end
kubi