用代码:
<code> func updateCarModelAndColorList(curCarSerieId:Int) { gLog.verbose("curCarSerieId=\(curCarSerieId)") NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.getCarModelColorCompleteHandler(_:)), name: kGetCustomerCarModelColorListComplete, object: curCarSerieId) SingletonCustomerVC().updateSingleCarModelAndColorList(curCarSerieId) } func getCarModelColorCompleteHandler(notif:NSNotification) { gLog.verbose("notif=\(notif)") let curCarSerieId = notif.userInfo!["curCarSerieId"]! as! Int gLog.verbose("curCarSerieId=\(curCarSerieId)") } func updateSingleCarModelAndColorList(curCarSerieId:Int) { if gCurUserItem.carModelDict.keys.contains(curCarSerieId) { gLog.info("global dict contain car model list for curCarSerieId=\(curCarSerieId)") NSNotificationCenter.defaultCenter().postNotificationName(kGetCustomerCarModelColorListComplete, object: self, userInfo: ["curCarSerieId" : curCarSerieId]) } else { getSingleCarModelColorList(IntentionSectionIndexCarModel, curCarSerieId: curCarSerieId) } </code>
是想要实现:
对于post事件时,回调函数handler中可以得到最开始的传入的参数
swift notification pass parameter in selector
ios – How to correctly pass selector as parameter in swift – Stack Overflow
objective c – How to pass object with NSNotificationCenter – Stack Overflow
最后去改为:
<code>// NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.getCarModelColorCompleteHandler(_:)), name: kGetCustomerCarModelColorListComplete, object: curCarSerieId) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.getCarModelColorCompleteHandler(_:)), name: kGetCustomerCarModelColorListComplete, object: nil) </code>
即可正常工作:
回调函数getCarModelColorCompleteHandler可以正常执行了。
[总结]
想要给NSNotification的回调函数selector中传递函数,则:
事件发布者:
<code>let kGetCustomerCarModelColorListComplete:String = "kGetCustomerCarModelColorListComplete" NSNotificationCenter.defaultCenter().postNotificationName(kGetCustomerCarModelColorListComplete, object: self, userInfo: ["curCarSerieId" : curCarSerieId]) </code>
事件接受者:
<code>NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.getCarModelColorCompleteHandler(_:)), name: kGetCustomerCarModelColorListComplete, object: nil) </code>
然后就可以正常接收到事件,执行回调函数了,获取之前传入的参数了:
<code> func getCarModelColorCompleteHandler(notif:NSNotification) { gLog.verbose("notif=\(notif)") let curCarSerieId = notif.userInfo!["curCarSerieId"]! as! Int gLog.verbose("curCarSerieId=\(curCarSerieId)") } </code>
注:
如果给事件接受者的object设置了值,比如self,当前的Int值:
<code>NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.getCarModelColorCompleteHandler(_:)), name: kGetCustomerCarModelColorListComplete, object: self) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.getCarModelColorCompleteHandler(_:)), name: kGetCustomerCarModelColorListComplete, object: curCarSerieId) </code>
好像就无法收到事件了
-》根本原因,暂时未去深究。