gpt4 book ai didi

iOS __kindof NSArray?

转载 作者:IT老高 更新时间:2023-10-28 11:48:45 26 4
gpt4 key购买 nike

作为开发人员,我一直在查看 iOS 9 的新功能,其中一些功能(例如 StackView)看起来很棒。

当我查看 UIStackView 的头文件时,我看到了这个:

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

NSArray* 上的 __kindof 是什么。我们现在可以在 NSArray * 上指定类型吗?

小测试:

@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

最佳答案

遗憾的是,当前投票最多的答案有点不正确。

您实际上可以添加<T> 的任何子类到一个通用集合:

@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!

但是当您尝试检索对象时,它将被严格键入为 <T>并且需要强制转换:

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

但是,如果您要添加 __kindof关键字返回类型将更改为kindof T并且不需要强制转换:

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

TLDR:Objective-C 中的泛型可以接受 <T> 的子类, __kindof关键字指定返回值也可以是 <T> 的子类.

关于iOS __kindof NSArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31399208/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com