Search code examples
objective-ccocoascripting-bridge

Looking for a better way to test an object's class type


In using Scripting Bridge with Excel, when I get the value of a single cell, I don't know what class I'm going to get from the cell. A range of a single cell so far returns an NSString or NSNumber (a range of multiple cells always returns an NSArray and I need to coerce the values from there). In my work, I usually only want the string value of the cell, so to coerce the value of a single-cell range into what I need, I do this...

NSString *cellValue = [targetRange.value get];
if ([cellValue isKindOfClass:[NSString class]]) {
    cellValue = [targetRange.value get];
} else if ([cellValue isKindOfClass:[NSNumber class]]) {
    cellValue = [[targetRange.value get] stringValue];
}

My problem lies with the first line (we'll ignore the third line for the time being as I'm still doing a bit of refactoring). Would there be a better class to capture the value of the cell to test for class against? Those last three lines work fine, but I don't feel entirely comfortable doing that; it seems unintuitive but going with NSObject feels just as weird.


Solution

  • it seems unintuitive but going with NSObject feels just as weird.

    In such cases you can use id:

    The id type is completely nonrestrictive. By itself, it yields no information about an object, except that it is an object.

    E.g.:

    id cellValue = [targetRange.value get];
    NSString *stringValue = nil;
    if ([cellValue isKindOfClass:[NSString class]]) {
        stringValue = cellValue;
    } else if ([cellValue isKindOfClass:[NSNumber class]]) {
        stringValue = [cellValue stringValue];
    }
    

    Note that in your case you could probably just use something like this:

    NSString *stringValue = [NSString stringWithFormat:@"%@", [targetRange.value get]];