Swift: returning data from child ViewController via NSNotificationCenter

I have a table view controller with a Sort button that I use to allow the user to change the sort order of the table. I go to the sort view controller when the button is clicked and pass the current sort order, which the UIPickerView selects and sets as the selected item.

If the user modifies the selected item in the picker, I want to send it back to the parent view controller so that it can re-sort the table.

So far I have seen 2 methods: creating a delegate or using NSNotificationCenter. I decided to try the latter.

In my SortViewController, I commit any changes to pickerView: didSelectRow: InComponent and then post the new value as a named notification.

In the parent view controller, I added an addObserver call to init for the view controller so that it listens for this notification, but no notifications are never sent, apparently.

here's the code:

TableViewController:

var sortOrder: String = "Name"

NSNotificationCenter.defaultCenter().addObserver(
    self,
    selector: "setSortOrder:",
    name: "sortOrderChangedNotification",
    object: sortOrder )

      

Receiver function:

func setSortOrder( notification: NSNotification ) {
    // set the sort order
    println("Received sortOrderChangedNotification")
}

      

SortViewController:

func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) {
    println("Picker view selection changed!")
    var selRow = sortPickerView.selectedRowInComponent(0)
    NSNotificationCenter.defaultCenter().postNotificationName("sortOrderChangedNotification", object: sortMethods[selRow] )
}

      

I never get println output from setSortOrder, which, as far as I know, could mean that: a) no notification is clicked (even though println in the didSelectRow file prints); b) it is not accepted by my observer; or c) my observer is not configured correctly.

Any input would be appreciated.

+3


source to share


1 answer


Your ad -addObserver:

should be like this:

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "setSortOrder:", name: "sortOrderChangedNotification", object: nil)    
}

      

Your ad -postNotificationName

should be like this:

NSNotificationCenter.defaultCenter().postNotificationName("sortOrderChangedNotification", object: nil, userInfo: ["row": sortMethods[selRow]]) //userInfo parameter has to be of type [NSObject : AnyObject]?

      



Then you can complete your method -setSortOrder:

with notification.userInfo

:

func setSortOrder(notification: NSNotification) {
    //deal with notification.userInfo
    println(notification.userInfo)

    println("Received sortOrderChangedNotification")
}

      

To stop monitoring:

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

      

+9


source







All Articles