What is __kindof?
__kindof is a new feature of the Objective-C language announced by Apple, together with other new features such as Nullability Annotations and Generics. Xcode 7 is needed to use __kindof
, so be sure to use that when going over through this post.
How to use __kindof in Objective-C?
Suppose we have this property:
1 |
@property (nonatomic, strong) NSArray *viewCollection; |
The developer reading this code will have an idea that the array must contain UIView
s, but it is not guaranteed that it will really contain UIView
s, until he reads through all of the code and verifies that indeed only UIView
s were inserted to the array. This case can be resolved using Objective-C’s new features, namely the Generics and __kindof
.
Using Generics, we can declare the property as the following instead.
1 |
@property (nonatomic, strong) NSArray<UIView *> *viewCollection; |
Anyone who reads this code will understand the array must contain UIView
s. But the catch is, the array must contain only UIView
s, but not instances of subclasses of UIView
s such as UIWebView
s or UIButton
s. Trying to insert a non-UIWebView
objectc will result to a compiler warning. This problem can be resolved using __kindof
.
1 |
@property (nonatomic, strong) NSArray<__kindof UIView *> *viewCollection; |
Using this construct, viewCollection
can contain instances of UIView
s and its subclasses such as UIWebView
s and UIButton
s.
Developers should use the new features of Objective-C if given the chance. The new __kindof
construct will surely help developers improve their code by being specific with their intents. The Generics construct and __kindof
seems strict but I think this is for the good of the developers and the apps that they are making.
References
https://developer.apple.com/videos/wwdc/2015/?id=401