The difference between __kindof and not using it in Objective-C

I read an article about some of the new objective-C features in iOS. However, I cannot understand what the main difference between these two methods is:

@property (strong, nonatomic, nonnull) NSArray<UIView *> *someViews;

and

@property (strong, nonatomic, nonnull) NSArray<__kindof UIView *> *someViews;

To me they look pretty similar. What is the difference, and when should I use one over the other?

+4
source share
3 answers

To see the full effect __kindof, I would recommend just using it and looking at different results:

NSMutableArray<UIView *> *views;
NSMutableArray<__kindof UIView *> *subviews;

views = [NSMutableArray new];
subviews = [NSMutableArray new];

UIView *someView = [UIView new];

[subviews addObject:someView];
[views addObject:someView];

UIButton *someSubview = [UIButton new];

[subviews addObject:someSubview];
[views addObject:someSubview];

So far for insertion into different shared arrays. Both compile and work just fine. No warnings, no crashes.

, , - - , UIView*, UIButton*

UIView *extView00 = views[0];
UIView *extView01 = subviews[0];
UIView *extView10 = views[1];
UIView *extView11 = subviews[1];

UIButton *extButton00 = views[0]; <-- warning
UIButton *extButton01 = subviews[0];
UIButton *extButton10 = views[1]; <-- warning
UIButton *extButton11 = subviews[1];

, :

, 'UIButton *' 'UIView *'

, . , , . - : extButton01 UIView*, UIButton*.

NSLog(@"%@", extButton00.titleLabel);
NSLog(@"%@", extButton01.titleLabel);
NSLog(@"%@", extButton10.titleLabel);
NSLog(@"%@", extButton11.titleLabel);

, , . views, , . , . , , . .

, . . 100% , X T, subviews __kindof.

, , .

+4

. :

UILabel* titleLabel = (typeof(titleLabel))someViews[0];

:

UILabel* titleLabel = someViews[0];

, : .

+2

, id foo, , foo - , foo ? kindof__ UIView* foo - , , foo - "" , foo, . :

UIView *bar = [[UIButton alloc] initWithFrame:CGRectZero];
[bar setTarget:nil];

, -setTarget: UIView. , :

[(UIButton*)bar setTarget:nil];

__kindof :

__kindof UIView *foo = [[UIButton alloc] initWithFrame:CGRectZero];
[foo setTarget:nil];

Here you tell the compiler what it foocan be of any kind, which allows you to relax a bit and allows you to call -setTarget:without dropping it on UIButton*. You can simply declare foohow id fooand get a similar effect, but specifying that foo- this is some kind of representation, gives the compiler more information to work with. In particular, it allows you to write Objective-C code that plays well with Swift, which is more strongly typed than Objective-C.

+1
source

Source: https://habr.com/ru/post/1616491/


All Articles