ios - How to remove observer defined without object and using block? -


within extension uiviewcontroller have method:

func setupuserandcartbuttons() {      let cartbarbuttonitem = uibarbuttonitem(image: dbcart.sharedcart().icon, style: .plain, target: self, action: selector("cartbuttontapped:"))      nsnotificationcenter.defaultcenter().addobserverforname(dborderschangednotficationname, object: nil, queue: nil, usingblock: { [weak self] notification in         print("---->\(self!.classforcoder)")         cartbarbuttonitem.image = dbcart.sharedcart().icon     }) } 

i use change image uibarbuttonitem.

this how push notification:

nsnotificationcenter.defaultcenter().postnotificationname(dborderschangednotficationname, object: nil) 

for every controller, within deinit, need remove observer:

nsnotificationcenter.defaultcenter().removeobserver(self, name: dborderschangednotficationname, object: nil) 

but doesn't work:

when push notification , deinit never called (what means never pop controller stack) looks ok, no crash, once pop @ least 1 view controller (deinit called then) , push notification, there crash:

fatal error: unexpectedly found nil while unwrapping optional value

you using addobserverforname:object:queue:usingblock: setup observer. in order later remove observer need use return value of method "observer" in calls removeobserver:... variants.

since setting observer in extension method of uiviewcontroller, , assuming calling concrete uiviewcontroller subclasses, i'd suggest updating method return observer

func setupuserandcartbuttons() -> nsobjectprotocol {      let cartbarbuttonitem = uibarbuttonitem(image: dbcart.sharedcart().icon, style: .plain, target: self, action: selector("cartbuttontapped:"))      let observer = nsnotificationcenter.defaultcenter().addobserverforname(dborderschangednotficationname, object: nil, queue: nil, usingblock: { [weak self] notification in         print("---->\(self!.classforcoder)")         cartbarbuttonitem.image = dbcart.sharedcart().icon     })      return observer } 

you have setup property in view controllers make use of method in order keep reference observer:

class dbsomeviewcontroller: uiviewcontroller {      var orderschangedobserver: nsobjectprotocol?      ... } 

then assign return value of setupuserandcartbuttons property:

orderschangedobserver = setupuserandcartbuttons() 

and remove observer in deinit:

deinit {     nsnotificationcenter.defaultcenter().removeobserver(orderschangedobserver) } 

credit

i can't take full credit answer dániel nagy pretty got in comment on question.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -