什么是id,與void *的區別
id在Objective C中是一個類型,一個complier所認可的Objective C類型,跟void *是不一樣的,比如一個 id userName, 和void *pUserName,[userName print] 是可以的,但[pUserName print] 在編譯時就會報錯,因為ObjeciveC的編譯器看到id,會假定它可以接受任何message,雖然在runtime時可能並不是這樣的,但pUserName並不是Objective C類型,編譯器就會報錯,但是void *有可能時可以接收print message的。
/** * Type for Objective-C objects. */ typedef struct objc_object { /** * Pointer to this object's class. Accessing this directly is STRONGLY * discouraged. You are recommended to use object_getClass() instead. */ #ifndef __OBJC_RUNTIME_INTERNAL__ __attribute__((deprecated)) #endif Class isa; } *id;
id 與 NSObject *的區別
id與instanceType
什么時候應該用id
- 當需要創建一個Collection類或者方法,這些類或方法接收各種不同類型時,比如NSArray中即可以接收NSString,又可以NSObject,還可以NSProxy,就需要用id;
- 當需要把某些信息作為context或者token 對象傳出給public API使用,而caller不能改變所傳出的對象時,就可以使用id作為類型;
init 方法的實現
convience constructor
http://tewha.net/2013/02/why-you-should-use-instancetype-instead-of-id/
http://stackoverflow.com/questions/7903954/why-use-id-when-we-can-just-use-nsobject