How to get the name of the "top" class in a class cluster?

242 Views Asked by At

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

1

There are 1 best solutions below

2
On

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.