UITableViewCell
的一個子類在awakeFromNib
中添加了觀察者NSNotificationCenter
。然而這個類也有一個隱含的解包可選屬性。什麼時候應該UITableViewCell帶隱式解包可選註冊通知?
class aCell: UITableViewCell() {
var aProperty: Int!
override func awakeFromNib() {
super.awakeFromNib()
NSNotificationCenter.defaultCenter().addObserver(...)
}
func notificationReceived() {
print(aProperty)
}
}
但awakeFromNib
被調用之前aProperty
可以設置:
let cell = tableView.dequeueReusableCellWithIdentifier(...)
cell.aProperty = 1
在通知的事件之前設置該屬性,則notificationReceived
訪問aProperty
而這是零和應用程序崩潰。
因此,如果我不想在設置屬性後手動將其作爲方法調用,應該在哪裏向通知註冊自己?
是否有必要aProperty是不可選?如果不打破業務邏輯,您可以使其成爲可選項。例如「var aProperty:Int?」 – firstinq
這是一個方便的問題,所以我不必總是打開它。 – Manuel
在這種情況下,您可以檢查屬性是否爲「notificationReceived」函數中的零,或者2.設置該屬性的初始值。 – firstinq