繁体   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