Philip Regan
Philip Regan

Reputation: 5055

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.

Upvotes: 1

Views: 134

Answers (2)

Georg Fritzsche
Georg Fritzsche

Reputation: 98984

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]];

Upvotes: 4

Joshua Nozzi
Joshua Nozzi

Reputation: 61228

Are you asking if it's "okay" or "normal" to inspect an object's class at runtime and act differently depending on the class? If so, that's an emphatic yes - that's part of what makes Objective-C so powerful.

If you're asking if there's a better way of determining an object's class, then no, not really. I mean you can directly compare classes ( == ) but that's not always wise, given class clusters, subclasses, etc.

Upvotes: 1

Related Questions