An NSObject is an NSObject… or is it?

Just got tripped up here. Was doing some runtime type checking… if an instance is this class, do this, if it’s this class, do this. A bit hacky, may clean it up later, but anyway…

I was using something like:

[c]if([[myObject className] isEqualToString:@”SomeClass”]) {…}[/c]

And it was working just fine.

In the simulator.

Then I tried it on the device. Suddenly, I’m getting crashes and with some investigation, find that “NSObject may not respond to className.” But I saw it in the docs! Honest! Let me look it up again… Wait, it’s not there anymore. Search a bit more… oh, yeah, there it is. WTF?

Turns out that OS X has a bit different version of NSObject than the iPhone does. Here’s the reference for the iPhone version:

https://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html

And here’s the OS X version:

http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html

You’ll see in the OS X version, there’s a “scripting” section that is missing in the iPhone version. And that’s where className lives.

“But wait,” you say, “You said it was working fine at one point.” Yes I did. In the simulator. Apparently, the simulator uses the OS X version, so you can merrily program away your iPhone app with APIs that don’t exist on the iPhone. And then it all blows up when you install it. Fantastic. Anyway, little heads up there. In case you run into that yourself.

This entry was posted in iPhone, Objective C. Bookmark the permalink.

5 Responses to An NSObject is an NSObject… or is it?

  1. Jerry Beers says:

    You can use [myObject isKindOfClass:NSClassFromString(@”SomeClass”)]

  2. kp says:

    Yeah, there are several alternate ways. I think I’m aware of most of them. The point I was trying to make is that the way I WAS using suddenly and inexplicably disappeared. 🙂

  3. In the 2.0 beta days I built out 3/4 of an application using the XML libraries available in the simulator. When trying to finally install to the phone I found out that library was included in the simulator framework, but excluded from the phone framework. I had to rebuild our entire api stack that night.

  4. Chris Hill says:

    This bit me, too. The developer of Cocoa-AMF has a pretty straightforward solution: create a category (which is probably what apple did in the first place).

    https://github.com/nesium/cocoa-amf/blob/master/CocoaAMF/NSObject-iPhoneExtensions.h

    https://github.com/nesium/cocoa-amf/blob/master/CocoaAMF/NSObject-iPhoneExtensions.m

Leave a Reply