[英]When should a UITableViewCell with implicitly unwrapped optional register for notifications?
UITableViewCell
的子類在awakeFromNib
中將觀察者添加到NSNotificationCenter
中。 但是,該類還具有一個隱式展開的可選屬性。
class aCell: UITableViewCell() {
var aProperty: Int!
override func awakeFromNib() {
super.awakeFromNib()
NSNotificationCenter.defaultCenter().addObserver(...)
}
func notificationReceived() {
print(aProperty)
}
}
但是可以在設置aProperty
之前aProperty
awakeFromNib
:
let cell = tableView.dequeueReusableCellWithIdentifier(...)
cell.aProperty = 1
如果在設置屬性之前收到通知,則notificationReceived
訪問aProperty
而該屬性為nil並且應用程序崩潰。
因此,如果我不想在設置屬性后手動將其作為方法調用,則該單元應在哪里注冊其通知?
嘗試盡早注冊該通知以避免崩潰是一個壞主意,因為您永遠不會做得太晚以至於無法百分百確定。
最好只檢查您所用的值是否為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.