Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between declaring a variable "id" and "NSObject *"?

Tags:

objective-c

In Objective-C, what's the difference between declaring a variable id versus declaring it NSObject *?

like image 597
eliego Avatar asked Jan 21 '09 20:01

eliego


People also ask

Is id an NSObject?

id is a language keyword but the NSObject is the base class in objective c. For id, you dont need to typecast the object. But for NSObject, you have to typecast it into NSObject.

How do I create an NSObject in Objective-C?

Creating a Custom ClassGo ahead an choose “Objective-C class” and hit Next. For the class name, enter “Person.” Make it a subclass of NSObject. NSObject is the base class for all objects in Apple's developer environment. It provides basic properties and functions for memory management and allocation.

What is id in Obj C?

id is a data type of object identifiers in Objective-C, which can be use for an object of any type no matter what class does it have. id is the final super type of all objects.


1 Answers

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.)

like image 82
Chuck Avatar answered Sep 21 '22 10:09

Chuck