I have View Controller (in ex. B) with AVPlayer for playing music. The problem is, I open this View Controller from another (in ex. A) VC by performing segue and passing the playlist object (songs list). Everything is working pretty fine for the first time, but when I perform segue again (not a unwind segue) to A VC, somehow (I believe) B VC still has the old values and is in the memory (?). And when I tap on another playlist and perform segue to B VC it starts playing music from the new playlist and somehow music starts playing from the old playlist and I get two AVPlayers which I cannot even kill. And if I repeat this step, the number of AVPlayers keeps increasing.

So, the question is (it's not about my code, so no need for that):

Does performing the segue kills the last VC instance(?) ?

If not, how should I present new VC and pass variables to it?

Question author Sphynx | Source



Never thought this would warrant a separate answer; thought this could be easily answered in comments. But I can't let this question exist with an answer provided by Amar here. It's wrong and doesn't make sense at all in the context.

That said, to answer your question, the reason why the instances aren't being killed because, the way you are doing -- performing segues on top of view controllers, builds up a stack that looks something like this:

A -> B -> A -> B -> A -> B

If you remember your Stack data structure, this is same as "pushing" elements onto a "stack of view controllers". This design "requires" all the instances of view controllers to remain in the memory. This explains why the music won't stop.

What kills B? Well, simply put "pop"ping the instance of B from this "stack", kills it.

You have :


You are now pushing B :

A -> B

Now if you want to go back to B. You pop B. Now the stack looks like this.


B is history. Notice how in the previous case of continuously pushing, B is alive and singing.

There are a couple of ways of popping a view controller from this stack in iOS. There are APIs like popViewController(:animated:) if you are building this on UINavigationController. There is dismissViewController(:animated:completion:) if you are modally presenting view controllers. And of course, there is the stated unwind segues help you pop the view controller.

Answer author Avismara

Ask about this question here!