所以我有两个 View Controller ,它们同时显示。目标如下:当我按下菜单时,它会返回一个索引。这将通知其他屏幕它需要更新。
我正在做以下事情:
Controller A(菜单)
func carbonTabSwipeNavigation(carbonTabSwipeNavigation: CarbonTabSwipeNavigation, didMoveAtIndex index: UInt) {
//NSLog("Did move at index: %ld", index)
//NSNotification to send data
NSNotificationCenter.defaultCenter().postNotificationName(NotificationNames.GetIndexCarbonKit, object: nil, userInfo: ["clickedIndex" : Int(index)])
}
Controller B(接收器)
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SearchResults.didReceiveNotification(_:)), name: NotificationNames.GetIndexCarbonKit, object: nil)
}
func didReceiveNotification(notification: NSNotification) {
let index:Dictionary<String,Int> = notification.userInfo as! Dictionary<String,Int>
let messageFromNotification = index["clickedIndex"]
print(" SearchResults now shows index: \(messageFromNotification)")
}
我的问题如下:我将索引从 A 发送到 B 的词典不断堆叠。因此,如果我多次按下菜单,我的输出如下:
SearchResults now shows index: Optional(0)
SearchResults now shows index: Optional(1)
SearchResults now shows index: Optional(1)
SearchResults now shows index: Optional(2)
SearchResults now shows index: Optional(2)
SearchResults now shows index: Optional(2)
SearchResults now shows index: Optional(3)
SearchResults now shows index: Optional(3)
SearchResults now shows index: Optional(3)
SearchResults now shows index: Optional(3)
SearchResults now shows index: Optional(1)
SearchResults now shows index: Optional(1)
SearchResults now shows index: Optional(1)
SearchResults now shows index: Optional(1)
SearchResults now shows index: Optional(1)
如何只获取最后一个索引?我不需要一堆其他的。
最佳答案
自己找到了正确答案。显然,我所要做的就是将 NotificationCenter 添加到 ViewWillAppear,并在 ViewWillDisappear 处将其删除。当我在 View 之间切换菜单时(相同 View 的 4 倍),它只返回一个值。
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SearchResults.didReceiveNotification(_:)), name: NotificationNames.GetIndexCarbonKit, object: nil)
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func didReceiveNotification(notification: NSNotification) {
let index:Dictionary<String,Int> = notification.userInfo as! Dictionary<String,Int>
self.currentIndex = (index.first?.1)!
print(currentIndex)
}
关于ios - NSNotification 用户信息在按下按钮时保持堆叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37859900/