ios - IBOutlet 属性应该标记为可空还是非空?

标签 ios objective-c xcode cocoa-touch nullable

在 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 中声明为 nonnull

最佳答案

如果您的类是用 Swift 编写的,则不能使用非可选属性,否则编译器会提示该属性从未初始化。这就是为什么 Apple 建议将其声明为隐式解包可选,因为一旦你的对象被初始化,你就可以确定该属性包含一个值(除非你有一个悬空的 socket ,顺便说一下......)

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

所以你可以这样做:

@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_resettablenull_unspecified。这并不是它们真正的目的,但它仍然会产生预期的结果。参见 this blog post有关这些注释的更多信息。

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

关于ios - IBOutlet 属性应该标记为可空还是非空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38644430/

相关文章:

ios - 为什么子类化是不可取的?

ios - 为什么在添加缺少的约束时图像会被拉伸(stretch)和压缩?

ios - 将 ARCamera 旋转变换应用于节点 (ARKit)

iphone - 从其他 ViewController 的 locationManager 方法访问 newLocation

ios - Google Analytics 3.03 iOS SDK 中的应用程序速度

ios - Xcode 4.3 和 4.3.1 破坏重构?

iphone - 为没有 Cydia 的越狱 iPhone 分发未签名的应用程序 iPhone

iOS- Adhoc Builds with Distribution Certification 推送通知出现两次

c++ - 跳转到 lldb 中的行号

iphone - UITableViewCell backgroundView 在不应该被重用时被重用