2016-04-14 54 views
3

的Xcode 7 added__kindof裝飾到對象的聲明:使用__kindof與非集合類型

KindOf。聲明爲__kindof類型的對象向編譯器表示「某種X」,並且可以在泛型參數中使用,以將類型約束到特定類或其子類。使用__kindof允許約束比顯式類更靈活,並且比僅使用id更明確。

__kindof最明顯的用例是使用集合類型來明確指定特定集合中的對象類型。從UIStackView頭:

- (instancetype)initWithArrangedSubviews:(NSArray<__kindof UIView *> *)views; // Adds views as subviews of the receiver. 
@property(nonatomic,readonly,copy) NSArray<__kindof UIView *> *arrangedSubviews; 

此明確指出,各NSArray將包含爲對象或UIView繼承。

但也有一些情況下,__kindof用在非集合類型的對象,如在UIStoryboardSegue頭:

@property (nonatomic, readonly) __kindof UIViewController *sourceViewController; 
@property (nonatomic, readonly) __kindof UIViewController *destinationViewController; 

什麼非集合類對象__kindof裝飾的變化?

+0

這是一個關於Objective-C的問題。您使用的IDE並不真正屬於您的問題。 – rmaddy

+0

@rmaddy是否有一個更好的標記,我應該使用一個對象裝飾器的東西,只能在特定版本的IDE或編譯器中使用?或者你覺得[tag:objective-c]標籤對於這個問題是足夠的。 – JAL

+0

我看不到任何其他標籤的原因。標題和問題使這一切足夠清楚。使用額外的標籤不會再顯示出來。 – rmaddy

回答

3

最明顯的例子是鑄造類型時:

UIViewController *vc = [[UIViewController alloc] init]; 
// SomeViewController inherits from UIViewController 
SomeViewController *someViewController = vc; // Warning: Incompatible pointer type initializing 'SomeViewController *' with an expression of type 'UIViewController *' 

__kindof UIViewController *otherVC = [[UIViewController alloc] init]; 
SomeViewController *someVC = otherVC; // no warning 

這就是爲什麼在UIViewControllerprepareForSegue方法,鑄造segue.destinationViewController另一個UIViewController小類不顯示警告:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
    SomeViewController *someVC = segue.destinationViewController; // no warning 
    // ... 
}