Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of id?

I am (trying to) learn Objective-C and I keep coming across a phrase like:

-(id) init;

And I understand id is an Objective C language keyword, but what does it mean to say "the compiler specifically treats id in terms of the pointer type conversion rules"?

Does id automatically designate the object to its right as a pointer?

like image 909
GPP Avatar asked Nov 02 '11 20:11

GPP


3 Answers

id is a pointer to any type, but unlike void * it always points to an Objective-C object. For example, you can add anything of type id to an NSArray, but those objects must respond to retain and release.

The compiler is totally happy for you to implicitly cast any object to id, and for you to cast id to any object. This is unlike any other implicit casting in Objective-C, and is the basis for most container types in Cocoa.

like image 93
joerick Avatar answered Nov 10 '22 13:11

joerick


id is a pointer to any Objective-C object (objc_object). It is not just a void pointer and you should not treat it as so. It references an object that should have a valid isa pointer. The values that can be stored in id are also not just limited to NSObject and its descendants, which starts to make sense of the existence of the NSObject protocol as well as the NSProxy class which does not even inherit from NSObject. The compiler will allow you to assign an object referenced by type id to any object type, assign any object type to id, as well as send it any message (that the compiler has seen) without warning.

like image 33
Joe Avatar answered Nov 10 '22 12:11

Joe


id is a generic type. This means that the compiler will expect any object type there, and will not enforce restrictions. It can be useful if you're expecting to use more than one class of objects there; you can then use introspection to find out which class it is. id automatically assumes a pointer, as all objects in Objective-C are passed as pointers/references.

Some Additional Resources:
id vs NSObject vs id*
Objective-C Programming (Wikibooks)
Introspection
Dynamic Typing

like image 31
FeifanZ Avatar answered Nov 10 '22 13:11

FeifanZ