In Objective-C, what's the difference between declaring a variable id
versus declaring it 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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With