iosnsnumbernsvalue

ObjC: differentiating between NSValue and NSNumber


I have some code where I will be receiving an object of unknown type. It could be a NSString, NSNumber, a scalar wrapped in a NSValue or some other class:

-(void) doSomethingWith:(id) value {
    if ( <test-for-NSValue> ) { 
        // Do something with a NSValue
    } else {
        // Do something else
    }
}

I need to identify where there is a scalar type inside a NSValue.

The problem is identifying a NSValue wrapped scalar vs a NSNumber. As NSNumber inherits from NSValue and both are class clusters, I'm haing trouble sorting them out.

So:

[value isKindOfClass:[NSValue class]] ... sees NSNumbers as NSValues.

[value isMemberOfClass:[NSValue class]] ... doesn't recognise NSValues because the instances are concrete subtypes.

Anyone got any idea how to do this?


Solution

  • What about:

    -(void) doSomethingWith:(id) value {
        if ([value isKindOfClass:[NSValue class]] && ![value isKindOfClass:[NSNumber class]]) {
           // NSValue but not instance of NSNumber
        } else {
           ...
        }
    }