Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid Modal Storyboard infinite loop

I've written a number of iOS applications a year ago on an old version of Xcode. I've just started a new project and discovered the storyboard feature in the latest Xcode. It turns out this is perfect for the application I am writing as it consists of ~30 interlinked screens.

My question is, how do I structure my storyboard and segues to allow my application to follow a circular path through my screens. I have seen a number of examples that simply segue screen 1 to screen 2 and then screen 2 to screen 1 using the modal option. This clearly works but when I debug an application built this way, it instantiates a new instance of each screen (view controller) for every segue performed. In the diagram below (apologies, I drew a nice picture but due to my newbie status, was not able to post it), how do I go from screen 1 to screen 2 to screen 3 and back to original screen 1 without creating a new instance?

// Screen 1 --> Screen 2 --> Screen3 
//     ^                         | 
//     |                         | 
//     +-------------------------+ 
like image 875
misthills Avatar asked Nov 06 '12 05:11

misthills


1 Answers

Ok, I have done a fair bit of research since posing this question and I believe that I can provide a reasonable answer to the question. In short, the approach I was proposing in the question is not compatible with the way that storyboards and segues actually work. Segues always instantiate a new instance of the view controller/view that it targets. This means that when we go from screen 3 back to screen 1, we are going to a new instance of screen 1, not the original. To resolve this, I will implement the storyboard slightly differently.

// Screen 1 --> Screen 2
//     |
//     +------> Screen 3

I will then confiure Screen 1 to listen for a 'next screen' message (via delegate/protocol) from screen 2 and 3.

When the user on screen 1 selects the button for screen 2, the storyboard and segue will handle the modal instantiation of Screen 2. When the user on screen 2 selects the 'Next Screen' button, instead of segueing to screen 3, I will dismiss screen 2 and have screen 1 launch Screen 3 via the new Screen 1 -> Screen 3 segue.

This approach has the advantage of allowing screen 1 to be the main controller for all the subsequent screens in the loop (in my instance I have 10 screens/exercises in the loop). The only disadvantage is that the storyboard doesn't nicely reflect the flow of the screens.

I hope that helps others attempting achieve the same thing in their iOS projects.

like image 143
misthills Avatar answered Oct 14 '22 10:10

misthills