36

I've been checking out iOS 9 new features as a developer and some of them like the StackView look awesome.

When I went the the header file of UIStackView I saw this:

@property(nonatomic,readonly,copy) NSArray<__kindof UIView *> *arrangedSubviews;

What is the __kindof on NSArray*. Are we able to specify a type on a NSArray * now?

Little test:

@interface DXTEST ()
@property (strong, nonatomic) NSMutableArray <__kindof NSString *>  *strings;
@end

@implementation DXTEST

- ( instancetype ) init {
    self = [super init];

    if( self ) {
        _strings = [NSMutableArray new];

        [_strings addObject:@(1)]; <-- compiler warning wieeeeee
    }

    return self;
}

@end
5
  • You are attempting to add the wrong type?
    – trojanfoe
    Commented Jul 14, 2015 at 6:33
  • That is the beauty! Before this would just work but now with __kindof it shows me i am adding the wrong type. But I cannot find any documentation so I don't know whats up
    – Haagenti
    Commented Jul 14, 2015 at 6:34
  • Nope; that's the use of generics, not __kindof.
    – trojanfoe
    Commented Jul 14, 2015 at 6:37
  • In Xcode 7, Objective-C supports Generics which allow you to specify type information for collection classes like NSArray, NSSet, and NSDictionary. developer.apple.com/library/prerelease/ios/documentation/…
    – Bannings
    Commented Jul 14, 2015 at 6:38
  • @trojanfoe I got it! I like this addition a lot in my current codebase
    – Haagenti
    Commented Jul 14, 2015 at 6:51

5 Answers 5

62

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>.

3
  • Yes, this is it, it avoids casting.
    – jpincheira
    Commented Jan 27, 2016 at 15:19
  • 1
    "Sadly the currently top voted answers are a bit incorrect" Hey, this is now the top voted answer.
    – Pang
    Commented Jun 28, 2017 at 4:55
  • 1
    Well then now the top voted answer is a bit incorrect, stating that itself is incorrect :)
    – Hooloovoo
    Commented Jun 14, 2018 at 9:03
41

Are we able to specify a type on a NSArray * now?

Yes, through Objective-C's new lightweight generics. In the example you provided, you have a property of type NSArray, which will accept elements that are UIViews.

Now, this can be specified as follows (without __kindof).

@property(nonatomic,readonly,copy) NSArray<UIView *> *arrangedSubviews;

And in this case, the array will accept objects whose class is UIView, but not any objects which are subclasses of UIView. The __kindof declaration marks the array's generic type as one which can accept both instances of the UIView class, and instances of any of UIView's subclasses.

Edit:

I've removed the bulk of my original answer since I mistakenly thought specifying the type of the array would prevent you from inserting objects of an incorrect type, and this is not the case. (Thanks to Artem Abramov for pointing this out. Please see his answer below for additional details)

Objective-C's generics seem to exist to give you type information when accessing the elements of a generic collection. For example, consider the following code which adds a UIView and a UIImageView to NSMutableArray<UIView *>. Both objects are inserted into the array without any complaints by the compilers or the runtime, but when you try to access the elements, you're warned by the compiler if the type of your variable is anything other than the generic type of the array (UIView), even if it's one of UIView's subclasses.

NSMutableArray<UIView *> *subviews = [[NSMutableArray alloc] init];

[subviews addObject:[[UIView alloc] init]]; // Works
[subviews addObject:[[UIImageView alloc] init]]; // Also works

UIView *sameView = subviews[0]; // Works
UIImageView *sameImageView = subviews[1]; // Incompatible pointer types initializing 'UIImageView *' with an expression of type 'UIView *'

NSLog(@"%@", NSStringFromClass([sameView class])); // UIView
NSLog(@"%@", NSStringFromClass([sameImageView class])); // UIImageView

Now, this produces a compile time warning, but does not crash at runtime. The key difference between this and the same example where the array's generic type is marked as __kindof, is that the compiler won't complain if you try to access ones of its elements, and store the result in a variable who's type is UIView or one of its subclasses.

NSMutableArray<__kindof UIView *> *subviews = [[NSMutableArray alloc] init];

[subviews addObject:[[UIView alloc] init]]; // Works
[subviews addObject:[[UIImageView alloc] init]]; // Also works

UIView *sameView = subviews[0]; // No problem
UIImageView *sameImageView = subviews[1]; // No complaints now!

NSLog(@"%@", NSStringFromClass([sameView class])); // UIView
NSLog(@"%@", NSStringFromClass([sameImageView class])); // UIImageView
6
7

iOS9 introduced lightweight generics on ObjC. ObjC is a really dynamic language while SWIFT prefer static types, to maximize interoperability and type checking now in ObjC you can declare an array like that:

NSArray<UIView *> *views;

That means that all the views object are instances of UIView objects, imagine the UIView subviews property it can contains elements that can be of different types, UIViews and objects that inherits from UIView, but the compiler will complain because even if they inherits they are different types.
That is were __kindof come into play. Is like to say that the array contains objects that are kind of type UIView.
Is like still using the advantage of an id type but restricted to a kind of class.

1
  • 1
    +1 I didn't know about the use of __kindof to allow subclasses. It's a shame Apple introduce a feature that works slightly differently to generics in every other language in this day and age.
    – trojanfoe
    Commented Jul 14, 2015 at 6:42
3

@Artem Abramov is correct. I want to point out additional point, as mentioned in Objective-C Generics

__kindof says this thing must be X or a more-derived class. Why is this necessary? The docs don't call this out but I suspect its because adding generics to Objective-C introduces a massive conundrum: If UIView.subviews is now NSArray<UIView *> then a whole lot of code is now invalid according to the compiler's type checker: [view.subviews[0] setImage:nil] is bogus because UIView doesn't have an image property. We've been spoiled by the fact that the Objective-C compiler will let you send any visible message selector to id... only now the subviews array doesn't return id, it returns UIView *. Oops.

__kindof solves that problem by saying the subviews array isn't explicitly an array of UIView * but an array of UIView * subclasses. Then the compiler will let you send any selectors that could apply to UIView * or all its subclasses, or assign an element from that array to a UIImageView *, but it will still complain if you attempt to do this: NSNumber *n = view.subviews[0].

And this is a feature of Clang introduced in Xcode 7. I don't think it is anything related to iOS version

2

If you have a function that returns __kindof SomeType *, then you're able to assign result of that function to a variable of type SubtypeOfSomeType * without the explicit cast. Without __kindof compiler will complain about incompatible types.

Actually there's at least one function like that in UIKit: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/index.html#//apple_ref/occ/instm/UITableView/dequeueReusableCellWithIdentifier:

Now let's extend that knowledge to NSArray. Specifying __kindof in generic type parameter adds that __kindof to return type of -objectAtIndex: and -objectAtIndexedSubscript: (well, actually to any method of generic NSArray that returns ObjectType), and now you can easily assign result of calling stackView.arrangedSubviews[i] to any variable that has a type that is a subclass of UIView or UIView itself.

Important note: you can store UIView subclasses in NSArray<UIView *> just fine, even without __kindof. __kindof is only about accessing elements of array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.