I’m creating an app using storyboards where a first screen has a list of songs in a table view and I want to pass that song to the next view (let’s call it the music player). I can accomplish this, but I also need to music player to keep track of various exercise statistics while the music player is playing music.
The problem is, if I enter the music player, go back to the song list view, and then select a cell again, it creates an entirely new instance of the music player. This is problematic as it creates a new timer and I lose all my exercise statistics. I also discovered that the original music player instance still exists because the timer continues to fire.
Is there anything I can do to make sure only one instance of the music player continues to appear?
Here is my current code (in order of execution):
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
self.nextScreen = [segue destinationViewController];
}
^ This stores the next screen as a member variable. I have to do this because prepareForSeque: is called before didSelectRowAtIndexPath: and I need to set data on the next view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
self.nextScreen.currentSong = [self.allSongs objectAtIndex:indexPath.row];
}
^This just sets the song.
I then proceed to set the next view up as needed in viewDidLoad:.
Is there a trick to fix this? If not, any suggestions how I get around this? I’m thinking one workaround is I’ll have to set up some sort of singleton, I’m just not sure if that’s the best option since I will need to reset the data so often.
Thanks!
You can’t do this with segues. Segues (with the exception of unwind segues) always create new instances when they are performed. You can push to your new controller (assuming your embedded in a navigation controller), and in the method where you do so, only create a new instance if it’s the first time.
You can still set up your controllers in the storyboard if you want, just don’t connect them together. In that case you would instantiate them with the following instead of using alloc init: