gpt4 book ai didi

objective-c - 将 __kindof 与非集合类型一起使用

转载 作者:搜寻专家 更新时间:2023-10-30 20:05:05 25 4
gpt4 key购买 nike

Xcode 7 added对象声明的 __kindof 装饰器:

KindOf. Objects declared as __kindof types express "some kind of X" to the compiler and can be used within generic parameters to constrain types to a particular class or its subclasses. Using __kindof allows constraints to be more flexible than an explicit class, and more explicit than just using id.

__kindof 最明显的用例是使用集合类型来明确说明特定集合中的对象类型。从 UIStackView header :

- (instancetype)initWithArrangedSubviews:(NSArray<__kindof UIView *> *)views; // Adds views as subviews of the receiver.
@property(nonatomic,readonly,copy) NSArray<__kindof UIView *> *arrangedSubviews;

这明确指出每个 NSArray 将包含属于或继承自 UIView 的对象。

但是在某些情况下,__kindof 用于非集合类型的对象,例如在 UIStoryboardSegue header 中:

@property (nonatomic, readonly) __kindof UIViewController *sourceViewController;
@property (nonatomic, readonly) __kindof UIViewController *destinationViewController;

__kindof 装饰器对非集合类型的对象有何改变?

最佳答案

最明显的情况是在转换类型时:

UIViewController *vc = [[UIViewController alloc] init];
// SomeViewController inherits from UIViewController
SomeViewController *someViewController = vc; // Warning: Incompatible pointer type initializing 'SomeViewController *' with an expression of type 'UIViewController *'

__kindof UIViewController *otherVC = [[UIViewController alloc] init];
SomeViewController *someVC = otherVC; // no warning

这就是为什么在 UIViewControllerprepareForSegue 方法中,将 segue.destinationViewController 转换为另一个 UIViewController 子类不显示警告:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
SomeViewController *someVC = segue.destinationViewController; // no warning
// ...
}

关于objective-c - 将 __kindof 与非集合类型一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36629886/

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