In Objective-C, what’s the difference between declaring a variable id versus declaring it NSObject *?
In Objective-C, what’s the difference between declaring a variable id versus declaring it NSObject
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
With a variable typed
id, you can send it any known message and the compiler will not complain. With a variable typedNSObject *, you can only send it messages declared by NSObject (not methods of any subclass) or else it will generate a warning. In general,idis 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 asid, 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 declaringNSObject*, though. Usually the conflict is between two more specific classes.)