![](/img/trans.png)
[英]What's the main difference between ReactiveCocoa and PromiseKit?
[英]What is main difference between “auto” and “instancetype” type?
auto
和clang類型instancetype
什么區別?
我們必須使用auto
和用戶instancetype
?
Objective C中的auto
繼承自C,表示auto關鍵字
將局部變量定義為具有本地生存期。
關鍵字auto使用以下語法:
[auto]數據定義; 由於本地生存期是局部變量的默認值,因此極少使用auto關鍵字。
注意:GNU C擴展auto關鍵字以允許嵌套函數的前向聲明。
如果您正在尋找C ++ 11的auto
或C#的var
-in的等價物,則使用Objective C id
。
id a = [NSString new];
id b = [NSNumber new];
但是在編譯時, id
沒有像c ++ 11中的auto
一樣解析為具體類型。
instancetype
是一個上下文關鍵字,可用作結果類型,表示方法返回相關的結果類型。 例如:
@interface Person
+ (instancetype)personWithName:(NSString *)name;
@end
與id不同, instancetype只能用作方法聲明中的結果類型。
使用instancetype,編譯器將正確地推斷出+ personWithName:的結果是Person的實例。 如果你試圖打電話會產生錯誤
[[Person personWithName:@"Some Name"] methodThatNotExistsInPerson];
如果您將使用id
編譯器不會這樣做,您將無法修復它並將收到運行時錯誤!
Instancetype用於為Objective C添加更多“強類型”。
如果你的意思是auto
他們是無關的。
auto
是C99存儲類。 存儲類定義變量和函數的范圍和可見性。 auto
是沒有說明符的局部變量的默認值。 其他是extern
, register
, static
。 Objective-C也有__block
,而C11有_Thread_local
。 instancetype
表示返回類型是
id
,LLVM將檢測不同類型之間的錯誤分配。 在構造函數和靜態初始化器中使用它。 1接收類是一個更好的術語,因為子類不需要重新定義instancetype
以使其返回子類類型。
正如其他人所說, auto
是一個很少使用的關鍵字,忘了它。
instancetype
是最近的一個介紹,它允許方法遵循init
模式。 在以init
開頭的Objective-C方法中,返回一個類型為接收類的對象 - 換句話說,該方法中的self
類型。 據說init
方法具有相關的結果類型 。 考慮:
@interface A : NSObject
- (id) initWithString:(NSString *)text;
@end
@interface B : A
@end
那么表達式:
[[A alloc] initWithString:@"An instance of A"]
編譯器知道結果的類型是A *
而不是為initWithString:
聲明的不太具體的id
initWithString:
因為initX
方法具有相關的結果類型。
表達的更多內容:
[[B alloc] initWithString:@"An instance of B"]
編譯器知道結果的類型是B *
,好像調用的方法來自A
類(通過繼承),它在B
的實例上調用。
instancetype
的引入允許其他方法聲明它們遵循這種模式,從而為編譯器提供更精確的類型信息 - 例如,它可以用來解析屬性引用。 考慮:
@interface A : NSObject
// returns an instance of A or whatever subtype of A it is called on
+ (instancetype) locateWithString:(NSString *)text;
@end
@interface B : A
@property NSInteger size;
@end
表達式:
[B locateWithString:@"An instance of B"].size
編譯器知道locateWithString:
返回一個B *
,因此具有屬性size
。 之前instancetype
類型id
將不得不被使用,並且類型id
沒有財產size
,因此編譯器將產生一個錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.