理解Objective C 中id

什麼是id,與void *的區別this

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的。.net

/**
 * 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與instanceTypeblog

 

何時應該用idtoken

  1. 當須要建立一個Collection類或者方法,這些類或方法接收各類不一樣類型時,好比NSArray中便可以接收NSString,又能夠NSObject,還能夠NSProxy,就須要用id;
  2. 當須要把某些信息做爲context或者token 對象傳出給public API使用,而caller不能改變所傳出的對象時,就能夠使用id做爲類型;

 

init 方法的實現ci

convience constructor get

 

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-nsobjectit

相關文章
相關標籤/搜索