1

I am creating an application that need to have a progress window in which i want to dynamically insert a subview for each item being processed, like Finder's copy files panel window. And also remove it dynamically when processing is done.

I want to use the same NSViewController view for all sub views, and I'm using an NSStackView to manage the views.

But, to make the sub views stay in memory I have to keep a strong reference to them, and the only way I know of is to create a property for each sub view i need to display. Like this:

@propery (strong) NSViewController *myViewController1;
@propery (strong) NSViewController *myViewController2;
@propery (strong) NSViewController *myViewController3;
@propery (strong) NSViewController *myViewController4;
....

I would like to know if there is a better, more dynamic way of doing this? Or do I have to create x number of properties for sub views to know i have enough instances to allocate, because I can't tell how many process views the user will need when running the application and exporting items.

I would therefore like to dynamically allocate each subview AND create a strong reference to it. Is that possible? Or is there another way of doing what I want?

Please let me know if I'm being unclear, I'll gladly explain more to get help with this problem.

  • How about just storing them in an array? – Ken Thomases Apr 01 '15 at 21:13
  • Yes, that could be done, but how do i do that and still keep the strong reference so the views don't get deallocated. I can add and remove as many as I want dynamically in my test code, but when trying to interact with the view I get a crash as it has been deallocated. Or am I not understanding your suggestion correct? – Erik Berglund Apr 02 '15 at 18:31
  • Arrays (i.e. `NSArray`s) keep strong references to their elements. You keep a single strong reference to an array, and you add the view controllers to the array (which keeps strong references to them). When you remove a view controller from the array, the array releases its reference. When the array is deallocated (after you release your strong reference to it, when your object is deallocated if not before), it also releases its references to all of its elements. – Ken Thomases Apr 02 '15 at 19:19
  • Thank you, that worked perfectly. I wish I could mark your comment as the correct answer. Such a simple solution, that I completely missed. – Erik Berglund Apr 03 '15 at 19:11

1 Answers1

1

You can store the references to the view controllers in an NSArray. Arrays keep strong references to the objects which they contain.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154