2016-08-23 28 views
0

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而這是零和應用程序崩潰。

因此,如果我不想在設置屬性後手動將其作爲方法調用,應該在哪裏向通知註冊自己?

+0

是否有必要aProperty是不可選?如果不打破業務邏輯,您可以使其成爲可選項。例如「var aProperty:Int?」 – firstinq

+0

這是一個方便的問題,所以我不必總是打開它。 – Manuel

+0

在這種情況下,您可以檢查屬性是否爲「notificationReceived」函數中的零,或者2.設置該屬性的初始值。 – firstinq

回答

0

試圖儘快註冊通知以避免崩潰是一個壞主意,因爲你永遠不會做到100%的確定。

這是更好地只檢查值不爲零,你的情況

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) 
    } 
} 
+0

,我知道,我想我將不得不使用Optionals,這真的很痛苦。因爲我知道這些參數永遠不會是零,一旦我設置它們。但是我不能使用我自己的初始化器,因爲初始化是由'dequeueReusableCellWithIdentifier'管理的。 – Manuel

相關問題