簡體   English   中英

帶有隱式展開的可選寄存器的UITableViewCell何時應發送通知?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM