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:
@property (nonatomic, strong) NSArray *viewCollection;
The developer reading this code will have an idea that the array must contain
UIViews, but it is not guaranteed that it will really contain
UIViews, until he reads through all of the code and verifies that indeed only
UIViews were inserted to the array. This case can be resolved using Objective-C’s new features, namely the Generics and
Using Generics, we can declare the property as the following instead.
@property (nonatomic, strong) NSArray<UIView *> *viewCollection;
Anyone who reads this code will understand the array must contain
UIViews. But the catch is, the array must contain only
UIViews, but not instances of subclasses of
UIViews such as
UIButtons. Trying to insert a non-
UIWebView objectc will result to a compiler warning. This problem can be resolved using
@property (nonatomic, strong) NSArray<__kindof UIView *> *viewCollection;
Using this construct,
viewCollection can contain instances of
UIViews and its subclasses such as
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.