RileyDev
RileyDev

Reputation: 2545

Refreshing Data when dismissing Modal

I have an reference to a managed object called selectedItem, I load the data in on view controller and have a modal segue (over current context) to another view to edit the title property of the selectedItem.

I expect a textLabel to refresh the data when dismissing the modal view but it does not. I have used the same method to add to the table data and it worked, because I use tableView.reloadData but how can I refresh the label data using the modal segue ? or basically have the label change to the new value.

detailsViewController

var selectedItem: Item!

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)
    self.tableView.reloadData()

    titleLabel.text = selectedItem.title

}

override func viewDidLoad() {
    super.viewDidLoad()

    titleLabel.text = selectedItem.title
}

EditViewController

@IBAction func save(sender: AnyObject) {

selectedItem.title = editTitle.text

    var error: NSError?
    if context!.save(nil){}
    context?.save(&error)


self.presentingViewController?.viewWillAppear(true)
self.dismissViewControllerAnimated(true, completion: {});

}

PS: I tried to do a work around by using another segue to go back to the first view but that crashed, does anybody know why ?

Upvotes: 0

Views: 458

Answers (1)

Fred Faust
Fred Faust

Reputation: 6800

You can use a NSNotification, they are pretty handy for this sort of thing, here's an example of some generic usage:

Parent View Controller

In viewDidLoad:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "udpateObject:", name: "udpateObject", object: nil)

In deinit:

NSNotificationCenter.defaultCenter().removeObserver(self, name: "udpateObject", object: nil)

Then you'll make a func that matches the selector of the observer:

func udpateObject(notification: NSNotification) {

// here you'll get the object you update in a different view

    if let receivedObject = notification.object as? YOUR_OBJECT_DATA_TYPE {

        self.ThisInstanceVariable = receivedObject
        // Update any UI elements
    }
}

Update View Controller

Wherever you update your data:

NSNotificationCenter.defaultCenter().postNotificationName("udpateObject", object: YOUR_UPDATED_OBJECT)

Upvotes: 1

Related Questions