Proper way to transit between two screens programmatically in iOS. Swift - ios

I have ViewController.swift files associated with storyboard (I use it for admob set up).
My UI is written in viewDidLoad function in each viewController class.
I have created segues in storyboard and use this code:
self.performSegueWithIdentifier("segueName", sender: nil)
Here is the problem. If I move between two screens back and forth, somehow the number of elements on the screen multiplied by two. I manage to find this due to this error:
Attempt to present VIEWCONTROLLER1 on VIEWCONTROLLER2 whose view is not in
the window hierarchy!
First time I back to the screen there is only one error. Next - 2, 4... Soon enough (back and forth between screens) delay becomes incredibly long like 15 seconds and doubles with each transition.
What is the problem and how to work around? Every time I move to the next screen remove all subviews on the previous?

The problem is you're recreating each VC each time you segue. From VC2, you need to call:
self.unwindForSegue("segueName", towardsViewController: FirstVC)
See also: UnwindForSegue

Related

Segue only working once?

Hi I made a game using SpriteKit and wanted to add a leaderboard using a UITableView. My segues are working perfectly from my GameViewController to the TableViewController and back. However I can only do this once. Once I am back to my GameViewController, tapping the same button wont take me to the TableViewController for the second time. Why is this happening?
I set it up so when a certain SKSpriteNode is tapped it segues to the the TableViewController. Currently I am using this line of code to segue from the GameViewController to the TableViewController (This code is within GameScene.swift)
self.view!.window!.rootViewController!.performSegueWithIdentifier("showScores", sender: self)
I then setup a Back button within a navigation bar and created a segue back to the GameViewController (by dragging the BarButtonItem to the GameViewController and selecting presentModally). Some help would be appreciated. Thanks!
I think you are segueing to the leaderboard, segueing back, but in the process adding the main game view to the stack rather than removing the leaderboard, so when you try to segue again, it is not the visible game scene that receives the call.
Try using this rather than a segue in your leaderboard code (where you ask to segue back to the game scene):
self.dismissViewControllerAnimated(true, completion: nil)
If that doesn't work use a delegate to ask the game scene to dismiss the leaderboard.
Edit: I was rambling and maxed out my word count for the comment, so thought I'd add my explanation here!
Think of the stack as a pile of paper, where each piece of paper is a viewController, the topmost piece being the one that's visible (naturally). When you segue or present a viewController modally you are adding a viewController to the stack or 'adding a piece of paper to your pile'. It is generally then a bad idea to segue to and from like you were doing because you are adding more and more 'pieces of paper' to the stack. You tend to get memory problems and/or irritating bugs :P. Instead what is considered best practice for programmatically going back is to do one of two things: if you are using a navigationController you should call popViewControllerAnimated, or if you aren't, like in this case, you should use dismissViewControllerAnimated. Both these functions take the topmost 'piece of paper' off the stack entirely. Fixing that problem of continually adding the viewControllers to the stack. If any of that was confusing (I'm writing this on my phone so could be!) just send me a comment or a message and I'll try to explain better! :)

What's causing this memory leak?

The Problem
I'm currently building an iPad game using SpriteKit. The gameplay is driven by sound provided by EZAudio. After running the Instrumentation tools to profile my app, I noticed that whenever the GameViewController is shown memory allocation jumps up. When I repeatedly show the screen (5+ times) it crashes the app. My project uses ARC.
Navigation
The navigation consists of 4 ViewControllers:
MenuViewController: This shows the menu
CharacterSelectionViewController: It lets you a pick a character to use
GameViewController: This lets you play a game with the player chosen
ScoreViewController: It shows you the score you achieved in the game
1 - MenuViewController
From here you can navigate to CharacterSelectionViewController via a Show (e.g. Push) segue.
2 - CharacterSelectionViewController
You can navigate to GameViewController via a Show (e.g. Push) segue. There is also a back button that goes back to MenuViewController with the following code:
[self.navigationController popViewControllerAnimated:YES];
3 - GameViewController
It first shows a 5 second countdown (using NSTimer)
The game starts with the character chosen in CharacterSelectionViewController
The game can be paused, allowing you to quit and go back to MenuViewController via a manual Show Detail (e.g. Replace) segue.
When the game ends, a manual Show (e.g. Push) segue is called that navigates to the ScoreViewController.
It's view hierarchy consists of three sets of view - one for the countdown, one for the pause menu and one for the game. These are subsequently shown/hidden. See the view hierarchy below:
4 - ScoreViewController
This allows you to quit or restart the game. When quit it pressed it performs a Show Detail (e.g. Replace) segue to MenuViewController. If restart is pressed it performs an unwind to CharacterSelectionViewController.
Responses
Please provide answers regarding:
How this kind of leak could occur
Any observations you have from the allocation and leaks screenshots
Allocation
Below, you can see the increasing allocations as I cycle through the apps screens to repeatedly show the GameViewController. I used Mark Generation to be able to show the increase in memory allocations.
Leaks
Here you can see the memory leak that occurred. This is ordered by size.
Ignore the leaks for the moment; fix the generational accretion first.
Is that generation snapshot representative of what is left after a typical snapshot? Typically, you'd want to show view controller, take snapshot, hide then show view controller, take snapshot, etc... as many times as you can without crashing (or 10 times if it doesn't crash).
Then look at generation 3 or 4 as that'll be the most stable representation of per-generation accretion.
If it is representative, it looks like you are leaking everything that the view controller would normally allocate. Ultimately, you are looking for the "root" of your object graph that is keeping everything around. Fix the reason why the root is sticking around and the rest'll likely go away.
I wrote a weblog post about this. It is a bit outdated, but the analysis workflow remains the same.
http://www.friday.com/bbum/2010/10/17/when-is-a-leak-not-a-leak-using-heapshot-analysis-to-find-undesirable-memory-growth/
How are you unwinding from your various view controllers? I note that you mention that when the game ends you're pushing another VC onto the stack, but I presume this VC chain will at some point unwind back to your initial menu? (In essence, I wonder if you're just looping around, hence adding new VCs to the stack everytime you play a game.)
To create an un-wind segue, simply create an empty method in the destination VC (i.e.: your main menu) as such:
- (IBAction)unwindToMainMenu:(UIStoryboardSegue*)sender
{
// Intentional NOP
}
(N.B.: Make sure it's also listed in the header.)
You can then call this as you would any other segue in your storyboard by dragging from the source object in question to the exit option at the top of the VC that contains the source object in the storyboard. This will present you with a list of segues to choose from. (You can verify that the segue is setup correctly by selecting the source object in the storyboard - the Connections inspector should list the unwind segue within the Triggered Segues section.)

App running slow after loading viewcontroller, then unload about 15-20 times

Using:
Xcode 4.6
Storyboards
ARC
Model segue to SecondViewController
I have an app that has the main ViewController that loads a new veiwController when the device is rotated to the right. When the app starts everything works great. If I rotate the device, then back which unloads the secondview controller, about 15-20 times the app is very slugish. I have narrowed down that it only happenes when the seconed view controller is loaded and only when i rotate the device a nunmber of times. I also have narrowed down that is is a memory issue. I installed an app that keeps track of the memory used and available. My memory goes from 400mb to 900mb used when i rotate the device a number of times. I am trying to give as much info as I can. Each view has 8 NSTimers that fire every second.
Is there a way to programmatic unload a view, to make sure is is being unloaded?
I have included this code to ensure the loading and unloading:
`- (void)setView:(UIView *)aView
{
NSLog(#">>> Entering %s <<<", PRETTY_FUNCTION);
if (!aView) // view is being set to nil
{
NSLog(#"Should be unloading now");
}
[super setView:aView];
NSLog(#"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}
log result:
2013-04-22 16:42:03.588 xxxxxxxx[xxxxxxx] >>> Entering -[GraphViewController setView:] <<<
2013-04-22 16:42:03.589 xxxxxxxx[xxxxxxx] <<< Leaving -[GraphViewController setView:] >>>
`
I am not sure what I need to be looking at to correct this.
Any "points" in the right direction will be very appreciated .
Thanks
You haven't given much information about how you "unload" SecondViewController. Are you doing a modal segue to it as well? If so, that's your problem -- every time you do a segue, you instantiate a new view controller, and if these are modal segues, the presented controller has a strong pointer to the presenting controller, so none of these controllers will ever get deallocated as you go back and forth.
As a rule, you should never go backwards in a storyboard using anything but an unwind segue. So, the solution to your problem is to use an unwind segue to go from SecondViewController back to MainViewController -- this will actually go back to the same instance of MainViewController that you came from, and SecondViewController will be deallocated. If you don't know how to make an unwind segue, I will edit my answer to show you how.
After Edit:
To make an unwind segues, you do two things. In the controller that you're going back to, you add a method -- the two important things are that it be an IBAction, and that it has a single argument that's typed to UIStoryboardSegue*. It doesn't matter what you call it, and it doesn't even need to have any code inside it, though I usually put in a log statement just to be sure it's called. Then, in IB in the controller you're unwinding from, you control drag from your UI element like a button or table view cell (or from the controller itself if you want to fire it from code), down to the green Exit icon at the bottom of the scene -- it's important to note that you are dragging from a UI element to the exit icon in the same controller, not between controllers. When you let go of the drag over the exit icon, you will see any methods you created with the signature I mentioned above. Choose the one you want, and that's it. You can implement prepareForSegue in the source controller just like any other segue if you want to pass any information back to the destination controller.

Memory management of view while using NavigationController

I changed navigation in my application from using UITabBarController to u UINavigationController. I.e. former solution (1st version) was based only on the TabBarController - 4 ViewControllers (one simple TableView, one simple custom view and one MapView with many overlays). The second version is based only on the UINavigationController.
In case of TabBarController it was clear and simple, everything worked fine, especially MapView. I mean: the MapView was loaded once (with a significant number of overlays) and when I went to another view and back to the MapView the MapView was still there with its overlays already loaded and displayed (simple check: MapView`s viewDidLoad was called just once per app run, I had some debug messages there).
Now I changed navigation logic to the UINavigationController. Everything works fine for the first look - but: the viewDidLoad (for each view) is called everytime I navigate to the view. It is annoying especially in the case of the MapView - the loading of overlays is performed everytime, it takes some time and it causes app crash in some cases.
OK, my questions:
Is it some kind of "common" behavior of NavigationController?
Can I change this behavior so viewDidLoad will be called just once?
And more - How can I influence the "display sequence" of some view?
I understand the logic is probably more complicated but I appreciate any answer or hint ;)
Some related circumstances:
TabBar and Navigation controllers are not combined.
I use storyboards, segues are designed in the UIB, no manual calling like perfomSegue or prepareForSegue in my code. One button triggers segue to MapView.
I use push segues.
I also tried to use modal segues but without any change of that behavior.
any of viewDidUnload is never called during segues among the views.
No memory warning received.
No memory leaks measured both on simulator and iPhone 4.
I tried to build a very simple temporary project / app that is concerned just about the Nav. Controller and other views without ANY coding, just storyboard. It was the same behavior.
There was an issue that causes app crash when I fast and periodically tapped to navigation button and back button between one view and the MapView. In most cases the app crashed when I tapped the back button on the MapView before it was fully displayed (i.e. its overlays). It was fixed when I added a 1 sec. delay method call in the viewDidDisappeared in the MapView. It is not a fair fix, I know ;)
A UITabBarController and UINavigationController are based on fundamentally different paradigms.
The UITabBarController is intended for the UIViewController on each tab to exist independently of each other and for the user to choose which they want to view. viewDidLoad only gets called once for each UIViewController because it is intended that each tab still exists in memory even as the user switches to a different tab.
The UINavigationController is a stack of UIViewControllers where each is related to the one above and beneath itself. The top UIViewController in the stack is always the one that is visible to the user. When a UIViewController is pushed to the stack, its viewDidLoad gets called because it is being loaded into memory. When the top UIViewControllergets poped off the stack, it is unloaded from memory, and viewDidUnload gets called on the way out (viewDidUnload is deprecated in iOS6 and won't get called, but the controller will still get dumped from memory). This is why viewDidLoad gets called every time that the user pushes a particular UIViewController onto the UINavigationController stack.

correcting navigation between VCs in existing app

I have a fairly simple app thats a game for small children. There is a main screen and 5 separate levels. 3 of the 5 levels are made up of more than one VC where actions take place in the first VC in that row then code calls a modal segue to the next one in the line and so on till it reaches the end of the row and a modal segue is called linking back to the main screen. The levels that have only one VC just perform actions then segue back to the main VC.
Every segue in the app in modal.
Also every page (VC) has a home button that will segue to the main page if pressed
I set this all up in the StoryBoard and visually everything works as Id expect but when adding sound I realized that there seems to be a major problem.
If I now understand correctly (and maybe I dont) modal segues dont actually replace the current VC with the newly requested one but rather slide the newly requested one over top the original and make it the visible display.
Currently I go from main to level 1. Level 1 does some stuff and plays some sounds that repeat via a timer. If I segue back to main visually everything is fine except the sounds being played by the timers in level 1 VC continue to play and xCdoe give me the following error quite a few times
2013-01-21 22:16:07.901 TTBetaDev[678:c07] Warning: Attempt to present <MainMenuViewController: 0x7e02f40> on <BonusViewController: 0x7ecbfa0> whose view is not in the window hierarchy!
Below is a screenshot of my storyboard in case I havent explained the layout well enough.
How should this be set up to allow the navigation I would like? A what steps will I need to take to apply that to the what I already have built in the storyboards? Or will I have to re-do all my storyborad work?
I tried apples VC documentation but I couldnt understand what relates to what Im trying to do.
COuld someone please help explain this to me
You have segues going forwards AND backwards. You shouldn't do this.
e.g. Look and Main and VC 2.
You have a segue going from Main to VC 2. This means that Main will present VC 2 as a modal view controller.
When Main does this though it is still on the stack underneath VC2.
Then you have a segue from VC2 to Main. This means that VC2 will create a new Main and present it modally too. If you continue using the app you will have multiple instances of main and all the other VCs and memory consumption will rocket.
What you need to do is delete ALL the segues that go backwards. (i.e. like the one from VC2 to Main)
Then when you want to get back to main from VC2 you have to dismiss VC2.
i.e.
in Main...
//present VC2
[self performSegueWithIdentifier:#"VC2Segue" sender:nil];
//dismiss VC2
[self dismissViewController:vc2ViewControllerInstance];
or in VC2...
//dismiss VC2 from itself
[self dismissViewController:self];
The main thing though is that you can't use segues to go backwards.
TL:DR
Nothing should segue INTO Main. Any segues that go into the left hand side of main should be deleted and dealt with properly.

Resources