3

Setup:

I have data coming in via JSON.

Using NSJSONSerialization I convert the JSON to an object.

A number value in JSON comes in Objective-C as several different possible class types:

(NSNumber, NSDecimalNumber or __NSCFNumber) - all of those are in the class cluster under NSNumber.


Problem:

1) I need a way to get the class cluster "umbrella" class - NSNumber, when I have a value of any of the types NSNumber, NSDecimalNumber or __NSCFNumber.

Same goes for strings. I need a way to get NSString, when I have any of these: NSString, NSMutableString, __NSCFString, __NSCFConstantString.

2) It could work also if I could get by code a list of all classes in the NSString cluster for example. Then I can build dynamically at run-time a list, and be sure it is complete.


What I have so far:

So far I couldn't come up with a sane way to do that. So I have a list of allowed types, but I'm afraid it might not be complete + it doesn't feel like the greatest solution there is.

Code: https://github.com/icanzilb/JSONModel/blob/master/JSONModel/JSONModel.m#L45

Bad Wolf
  • 8,206
  • 4
  • 34
  • 44
Marin Todorov
  • 6,377
  • 9
  • 45
  • 73

1 Answers1

2

You can do this:

id object = // obtain the object somehow

Class cls = Nil; // for now

// property list types, roughly equivalent to JSON's fundamental types
NSArray *classes = @[[NSString class], [NSNumber class], [NSArray class], [NSDictionary class], [NSData class], [NSDate class]];

Class c;
for (c in classes) {
    if ([object isKintOfClass:c]) {
        cls = c;
        break;
    }
}

you can extend the list by adding other classes to the classes array. In the end, cls will contain the class cluster of which object is an instance, or Nil if it isn't an instance of either one.

  • This works for Core Foundation classes. Keep in mind that there might be more Class Clusters out there. – Berik Feb 27 '13 at 10:31
  • @Berik I didn't state/imply this is universal, nor did OP's problem need it to be so. –  Feb 27 '13 at 12:16