So I have two viewcontrollers, which are shown at the same time. The goal is the following: when I press the menu, it gives back an index. This will notify the other screen that it needs to update.
I am doing the following:
Controller A (the menu)
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 (the receiver)
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)")
}
My issue is the following: the Dictionary in which I'm sending the index from A to B, keeps stacking. So if I press the menu multiple times, my output is the following:
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)
How can I only get the last index? I don't need a stack of the others.
Found the correct answer myself. Apparently all I had to do was add the NotificationCenter to the ViewWillAppear, and remove it at the ViewWillDisappear. When I switch in the menu between the views (which is 4 times the same view) it only gives back one value.
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)
}