Created
February 18, 2013 20:41
-
-
Save kristopherjohnson/4980518 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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