Reputation: 8462
I have a NSDictionary and what to get the datatype for value given the key
is it possible?
Upvotes: 2
Views: 1077
Reputation: 3001
You could check the variants you accept by
id objectValue = [dictionary valueForKey:@"SomeKey"];
if ([objectValue isKindOfClass:[NSString class]]) {
//Object is a NSString
} else if ([objectValue isKindOfClass:[NSArray class]]) {
//Object is a NSArray
} else if ([objectValue isKindOfClass:[NSDictionary class]]) {
//Object is a NSDictionary
} else if ([objectValue isKindOfClass:[NSNumber class]]) {
//Object is a NSNumber
}
And so on.. In this pattern just handle all the types your app supports. Ignore values your app doesn't support by this pattern or just fail gracefully in another way when you don't support the datatype of the value
To just figure out what class it is (to debug the application for example) you can do:
NSString *className = NSStringFromClass([objectValue class]);
Upvotes: 4
Reputation: 8029
you could use NSStringFromClass
to get the type, or failing that you could use isKindOfClass:
NSDictionary *dictionary = @{
@"string": @"Something",
@"number": @(1),
@"null": [NSNull null],
@"custom": [[CustomType alloc] init]
};
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"type = %@", NSStringFromClass([obj class]));
}];
output:
type = CustomType
type = NSNull
type = __NSCFNumber
type = __NSCFConstantString
Upvotes: 0