iOS __kindof NSArray?

Sadly the currently top voted answers are a bit incorrect.

You actually can add any subclass of <T> to a generic collection:

@interface CustomView : UIView @end
@implementation CustomView @end

NSMutableArray<UIView *> *views;
UIView *view = [UIView new];
CustomView *customView = [CustomView new];
[views addObject:view];
[views addObject:customView];//compiles and runs!

But when you’ll try to retrieve the object, it will be strictly typed as <T> and will require casting:

//Warning: incompatible pointer types initializing 
//`CustomView *` with an expression of type `UIView * _Nullable`
CustomView *retrivedView = views.firstObject;

But if you’ll add __kindof keyword the returned type will be changed to kindof T and no casting will be required:

NSMutableArray<__kindof UIView *> *views;
<...>
CustomView *retrivedView = views.firstObject;

TLDR: Generics in Objective-C can accept subclasses of <T>, __kindof keyword specifies that return value can also be subclass of <T>.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)