0

new to ARC, still getting used to not having autorelease (which was one of my favorite features of Objective-C). Found myself having a bit of trouble solving what used to be a very simple problem:

Let's say I have navigation controller N, viewController A, and viewController B. Let's also say that viewController B is an ivar in viewController A.

Now suppose A is pushed to N. A displays a button which, when pressed, will cause B to be instantiated and pushed to N. So now A and N are both retaining B.

When the back button is pressed, N pops B off the stack. At this point I'd like B to dealloc, as it's not being used and taking up lots o memory—but A is still retaining B (because A has a strong reference to it's ivars).

I'm solving this problem by having A be the navigationController's delegate and responding to navigationController: didShowViewController: animated:

This works, but is very clearly not a good pattern. What is the proper way to deal with this kind of setup in ARC.

Thanks!

6
  • 1
    Why do you have a viewControllerB ivar in viewControllerA? What is its purpose?
    – rdelmar
    May 29, 2015 at 23:05
  • Not sure why you're doing this but declare the viewController B property as weak rather than strong. That way, viewController B will be dealloced once no more references are held to it by the navigation controller. May 29, 2015 at 23:06
  • No can do. This gives the warning Assigning retained object to weak variable; object will be released after assignment. And its not kidding. The ivar is nil in the very next line of code after it's instantiated. Which means it's nil before I can even have the navigation controller push it. Someone has to own B, and I DO want that someone to be A (at least that would make the most sense to me). May 29, 2015 at 23:10
  • 3
    You have to instantiate into a local variable and then assign it to your weak property so that something is holding a strong reference before you present it. The local variable's strong reference will be released once the method exits
    – Paulw11
    May 29, 2015 at 23:35
  • When you're done with it, just set your ivar to NULL and let ARC do it's thing. You can test by overriding dealloc(don't call super) and printing something in your viewcontroller and it will get called when arc destroys it.
    – dave234
    May 29, 2015 at 23:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.