Storyboard segues causing memory leaks

You aren’t using the modal segues correctly. The way you have implemented it, you are creating a new instance of each view controller when you segue instead of returning to the instance you came from. That is why your memory usage continues to increase.

Before iOS 6, the correct way to handle this was to:

1) define a method such as viewController2Done in view controller 1
2) in view controller 2, create a property called delegate of type id.
3) in prepareToSegue for view controller 1, set delegate in view controller 2 to self
4) in view controller 2, when it is time to return to view controller 1, call [delegate viewController2Done]
5) in viewController2Done call [self dismissModalViewControllerAnimated:YES]

This method still works in iOS 6, but there is also a new unwind segue that can be used instead. To use it, you would define a method in your view controller 1 like so:

Objective-C:

- (IBAction)unwindFromViewController2:(UIStoryboardSegue *)segue
{
    NSLog(@"and we are back");
}

Swift:

@IBAction func unwindFromViewController2(_ segue: UIStoryboardSegue) {
    print("and we are back")
}

Then you’d control drag from the button in view controller 2 to the orange exit icon in the bar above the view controller in the Storyboard. In the pop up, you’d select unwindFromViewController2 and voila, you’re done.

enter image description here

Leave a Comment