简体   繁体   中英

When should a UITableViewCell with implicitly unwrapped optional register for notifications?

A subclass of UITableViewCell adds observers to NSNotificationCenter in awakeFromNib . However the class also has an implicitly unwrapped optional as property.

class aCell: UITableViewCell() {

   var aProperty: Int!

   override func awakeFromNib() {
      super.awakeFromNib()

      NSNotificationCenter.defaultCenter().addObserver(...)
   }

   func notificationReceived() {
      print(aProperty)
   }
}

But awakeFromNib is called before aProperty can be set:

   let cell = tableView.dequeueReusableCellWithIdentifier(...)
   cell.aProperty = 1

In the event of a notification before setting the property, the notificationReceived accesses aProperty while it is nil and the app crashes.

So where should the cell register itself for notifications if I don't want to manually call it as a method after setting the property?

Trying to register for the notification as late as possible to avoid a crash is a bad idea because you will never do it late enough to be 100% sure.

It's better to just check that the value is not nil in your case

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM