What’s the difference between declaring a variable “id” and “NSObject *”?

With a variable typed id, you can send it any known message and the compiler will not complain. With a variable typed NSObject *, you can only send it messages declared by NSObject (not methods of any subclass) or else it will generate a warning. In general, id is what you want.

Further explanation: All objects are essentially of type id. The point of declaring a static type is to tell the compiler, “Assume that this object is a member of this class.” So if you send it a message that the class doesn’t declare, the compiler can tell you, “Wait, that object isn’t supposed to get that message!” Also, if two classes have methods with the same name but different signatures (that is, argument or return types), it can guess which method you mean by the class you’ve declared for the variable. If it’s declared as id, the compiler will just throw its hands up and tell you, “OK, I don’t have enough information here. I’m picking a method signature at random.” (This generally won’t be helped by declaring NSObject*, though. Usually the conflict is between two more specific classes.)

Leave a Comment