[英]When should a UITableViewCell with implicitly unwrapped optional register for notifications?
A subclass of UITableViewCell
adds observers to NSNotificationCenter
in awakeFromNib
. UITableViewCell
的子类在awakeFromNib
中将观察者添加到NSNotificationCenter
中。 However the class also has an implicitly unwrapped optional as property. 但是,该类还具有一个隐式展开的可选属性。
class aCell: UITableViewCell() {
var aProperty: Int!
override func awakeFromNib() {
super.awakeFromNib()
NSNotificationCenter.defaultCenter().addObserver(...)
}
func notificationReceived() {
print(aProperty)
}
}
But awakeFromNib
is called before aProperty
can be set: 但是可以在设置aProperty
之前aProperty
awakeFromNib
:
let cell = tableView.dequeueReusableCellWithIdentifier(...)
cell.aProperty = 1
In the event of a notification before setting the property, the notificationReceived
accesses aProperty
while it is nil and the app crashes. 如果在设置属性之前收到通知,则notificationReceived
访问aProperty
而该属性为nil并且应用程序崩溃。
So where should the cell register itself for notifications if I don't want to manually call it as a method after setting the property? 因此,如果我不想在设置属性后手动将其作为方法调用,则该单元应在哪里注册其通知?
Trying to register for the notification as late as possible to avoid a crash is a bad idea because you will never do it late enough to be 100% sure. 尝试尽早注册该通知以避免崩溃是一个坏主意,因为您永远不会做得太晚以至于无法百分百确定。
It's better to just check that the value is not nil in your case 最好只检查您所用的值是否为nil
class aCell : UITableViewCell
{
var aProperty: Int!
override func awakeFromNib() {
super.awakeFromNib()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(notificationReceived(_:)), name: "...", object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func notificationReceived(notification: NSNotification) {
guard let aProperty = self.aProperty else {
return
}
print(aProperty)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.