0

I have a class called ContentViewControllerPartial extending UIViewController. I instantiate it several times using content = [self.storyboard instantiateViewControllerWithIdentifier:@"ContentViewControllerPartial"]; expecting to get a new instance each time.

In my class I have an instance variable:

@implementation ContentViewController ... AVPlayer* mPlayerAV;

which is instanciated during viewDidLoad:

- (void)viewDidLoad {
    [super viewDidLoad];
    ...
    if ( !mPlayerAV )
    {
       mPlayerAV = [AVPlayer playerWithURL: videoURL];
    }

To my surprise, each of my ContentViewControllerPartial classes shared the same instance of mPlayerAV! This was obvious by the fact that it was not nil on the 2nd and 3rd instancations.

Only when I have turned mPlayerAV to a property, I got the expected behaviour - mPlayerAV was no longer shared between instances, and was nil.

What is going on here? How come a private instance variable is shared between instances?

Vaiden
  • 15,728
  • 7
  • 61
  • 91
  • have you check to see that it have the same address? – YYfim Feb 07 '15 at 00:19
  • No, but it was not nill and had the same KVO as the original one so I deducted it was the same. – Vaiden Feb 07 '15 at 00:21
  • if you can do a quick check to see if the addresses are the same..dunno if that is the case, but can't hurt – YYfim Feb 07 '15 at 00:28
  • I agree with @YuviGr, don't deduce, look at the addresses to see if they are in fact the same instance. – rdelmar Feb 07 '15 at 00:29
  • Checked. The same: 0x1736d080 – Vaiden Feb 07 '15 at 00:34
  • Also - on the debugger - it does not appear in the list of instance variables. – Vaiden Feb 07 '15 at 00:35
  • I don't see this behavior when I try it. You should show the relevant code for ContentViewControllerPartial, and where you're instantiating new ones. – rdelmar Feb 07 '15 at 00:47
  • You said making it a property fixed it? Was it declared static originally or in the .m file outside the implementation? Sounds like it acted like a static variable. If so each viewDidLoad would reset it to a new AVPlayer but they would all end up the same. – Rory McKinnel Feb 07 '15 at 00:48
  • I had a similar issue. It wasn't in { } like normal instance variables. I believe putting it in the {} fixed the issue for me. However I avoid instance variables and use properties. – Skyler Lauren Feb 07 '15 at 00:51
  • Was not static. Please review my edits. Thanks. – Vaiden Feb 07 '15 at 00:53
  • How are you determining that each of the instances was the same? By logging or with the debugger? Please elaborate on how you're actually doing this. – rdelmar Feb 07 '15 at 01:06

1 Answers1

1

If you don't put your instance variables in {} it creates a global instead of an instance variable.

The post here does a great job of do's and don'ts for iVars.

Judging by the code provided I believe this explains the odd behavior. I hope that helps.

Community
  • 1
  • 1
Skyler Lauren
  • 3,792
  • 3
  • 18
  • 30