我在 viewController 中使用的自定义视图有问题。
假设自定义 xib 视图(AddButtonWithOptions,一个在点击时显示一些选项的按钮)正在使用界面构建器添加到 ViewController。
在 viewDidDisappear 函数上,我正在关闭该按钮的选项。像这样:
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if createButton.isOn {
createButton.switchOptionState()
}
}
通常,操作完美无缺,当视图消失时 VC 正在关闭选项。但是在 crashlytics 上,我从这行代码中得到一个错误:
if createButton.isOn {
报告是:崩溃:com.apple.main-thread EXC_BREAKPOINT 0x00000001005592a0 SalesInvoicesHomeViewController.viewDidDisappear(_:) + 194
我无法重现该错误,因为该按钮永远不会为零。
这是我在 viewController 上的按钮实例:
@IBOutlet weak var createButton: AddButtonWithOptions!
这就是我实现自定义 xib 按钮设置的方式:
// Button options
var options: [AddButtonOption] = [] {
didSet {
setupOptions()
}
}
/// Flag determines whether state is extended or reduced
var isOn: Bool = false
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
customInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
customInit()
}
final func customInit() {
Bundle(for: AddButtonWithOptions.self).loadNibNamed("AddButtonWithOptions", owner: self, options: nil)
self.addSubview(view)
view.frame = self.bounds
}
// Programmatic initializer
class func instanceFromNib() -> AddButtonWithOptions {
return UINib(nibName: "AddButtonWithOptions", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! AddButtonWithOptions
}
// MARK: UI Setup: Create an add button for each option
/// This method is called when options are passed into this component. It simply sets the state to reduced, inits option views and adds them into the options stack container, and assigns delegations
private func setupOptions() {
mainAddButton.delegate = self
// Include options
optionsContainer.isHidden = true
optionsContainer.alpha = 0.0
for option in options {
let addButtonOptionView = AddButtonOptionView.instanceFromNib()
addButtonOptionView.addButtonOption = option
addButtonOptionView.delegate = self
optionsContainer.addArrangedSubview(addButtonOptionView)
}
reduceOuterContainer()
}
这就是我关闭选项的方式:
func switchOptionState() {
isOn = !isOn
isOn ? extend() : reduce()
}
我认为问题的发生是因为 ARC。正如我所想,它会在一段时间后从内存中清除我的 xib 视图。
这种情况怎么会发生?