ios – IBOutlet属性是否应标记为可空或非空?

前端之家收集整理的这篇文章主要介绍了ios – IBOutlet属性是否应标记为可空或非空?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Objective-C中,我习惯于声明连接到Interface Builder的属性

@property (nonatomic,weak) IBOutlet UIView *myView;

现在我有一个使用新的XCode可空性属性的类.为了保持与Swift的兼容性,IBOutlet应该具有哪些可空属性?根据Apple的“Using Swift with Cocoa and Objective-C”:

When you declare an outlet in Swift,you should make the type of the outlet an implicitly unwrapped optional. This way,you can let the storyboard connect the outlets at runtime,after initialization. When your class is initialized from a storyboard or xib file,you can assume that the outlet has been connected.

那么这是否意味着在Objective-C中应该将插座声明为非空的?

解决方法

如果您的类是用Swift编写的,则不能使用非可选属性,否则编译器会抱怨该属性从未被初始化.这就是为什么Apple建议将它声明为一个隐式解包的可选项,因为一旦你的对象被初始化,你就确定该属性包含一个值(除非你有一个悬挂的插座,这可能发生在……)

从Objective-C导出时,您可以将其标记为非空,并且它将作为非可选属性出现在Swift中,在这种情况下很好.请注意,您不能同时使用nonnull和weak.

所以你可以这样做:

@property (nonatomic,strong,nonnull) IBOutlet UIView *subview;
// Exported to Swift as @IBOutlet var subview: UIView

要么

@property (nonatomic,weak,nullable) IBOutlet UIView *subview;
// Exported to Swift as @IBOutlet weak var subview: UIView?

如果由于某种原因,您仍希望将属性作为隐式展开的可选项导出到Swift,则可以将该属性标记为null_resettable或null_unspecified.这不是他们的意思,但它仍然会产生预期的结果.有关这些注释的更多信息,请参见this blog post.

@property (nonatomic,null_unspecified) IBOutlet UIView *subview;
// Exported to Swift as @IBOutlet weak var subview: UIView!

猜你在找的Xcode相关文章