Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save li-jun/f298db349beef998177eae26a268f9a1 to your computer and use it in GitHub Desktop.
Save li-jun/f298db349beef998177eae26a268f9a1 to your computer and use it in GitHub Desktop.
Category on NSDictionary that will convert string values to numbers or vice versa. Useful for JSON deserialization.
#import <Foundation/Foundation.h>
@interface NSDictionary (XXXConvertValues)
// Return value associated wth key, converted to NSString
- (NSString *) stringValueForKey:(id)key;
// Return integer value associated with key, converted to integer
- (NSInteger) integerValueForKey:(id)key;
// Return double value associated with key, converted to double
- (double) doubleValueForKey:(id)key;
@end
#import "NSDictionary+XXXConvertValues.h"
@implementation NSDictionary (XXXConvertValues)
- (NSString *) stringValueForKey:(id)key {
id obj = [self objectForKey:key];
if ([obj isKindOfClass:[NSString class]]) {
return obj;
}
else if ([obj isKindOfClass:[NSNumber class]]) {
return [obj stringValue];
}
else {
return [obj description];
}
}
- (NSInteger) integerValueForKey:(id)key {
id obj = [self objectForKey:key];
if ([obj respondsToSelector:@selector(integerValue)]) {
return [obj integerValue];
}
else {
return 0;
}
}
- (double) doubleValueForKey:(id)key {
id obj = [self objectForKey:key];
if ([obj respondsToSelector:@selector(doubleValue)]) {
return [obj doubleValue];
}
else {
return 0;
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment