0

I am new to Swift and trying to add a string to an array in the previous viewController. In my main view controller I have this method to declare the viewController

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        var newSoundViewController = segue.destinationViewController as! NewSoundViewController
        newSoundViewController.previousViewController = self
}

In the NewSoundViewController, I have a method that adds a string to the array of the previous viewController. Here is that code:

@IBAction func saveTapped(sender: AnyObject) {
    var sound = Sound()
    sound.name = soundTextField.text
    self.previousViewController.sounds.append(sound)
    self.dismissViewControllerAnimated(true, completion: nil)
}
jhamm
  • 24,124
  • 39
  • 105
  • 179

1 Answers1

2

You can do few things about that:

-Unwind segue ( What are Unwind segues for and how do you use them?)

-Delegate: You can create @protocol and define method there, declare delegate(second class), confront the protocol in your first class, and then simply call self.delegate.thatMethod.

For completness sake, you can use few more things:

-Singleton class

-Core data.

Unwind segue is the best for your solution since you need communication between two controllers that are next to each other. They don't need to be next to each other but to be in the same navigation stack (Thanks to @ABakerSmith)

Delegate is good when you need to communicate between distant controllers.

Singleton is usualy used for configuration and Core data is something like database. These last two is not appropriate for your case, so I would use unwind segue.

Community
  • 1
  • 1
Miknash
  • 7,888
  • 3
  • 34
  • 46
  • Good answer, just thought I should mention that to use an unwind segue the view controllers don't have to be 'next to each other' - you can segue back to any view controller so long as it's in the hierarchy of presented view controllers. – ABakerSmith Apr 24 '15 at 14:03
  • Yeah, my fault. What I meant is that unwind should be used in navigation hierarchy. Thanks for point out – Miknash Apr 24 '15 at 14:06