Search code examples
iosautomatic-ref-countingnsobjectdealloc

Dealloc an NSObject using ARC


I have multiple view controllers with a strong reference to a subclass of NSObject. Each view controller allows the user to mutate this object in some fashion and then passes the object to the next view controller. Once completed the user can commit these changes and start the process all over with a new instance of the NSObject subclass. The problem I am experiencing is that some of the view controllers on the stack are retaining the reference to the committed instance.

I have tried using weak, and unsafe_unretained but that makes it difficult to pass the object between view controllers.

I basically need to dealloc an instance of the object once committed, so that any view controllers' reference to it will be nil. However, ARC doesn't allow explicit calls to dealloc.

I can solve this using NSNotificationCenter or by using a delegate, but is there a cleaner way of doing this?

Any insight would be very much appreciated. Thanks!


Solution

  • The model object (the object that everyone mutates) should be owned by a central "Model" class. You can pass that around. It could have a method such as currentRecord or the like. That way, all your view controllers can either have a weak reference to the current record, or they could just ask the Model for it each time they need it. View Controllers should never "own" data objects.

    This means that the view controllers can use KVO to observe when currentRecord changes. It alternately gives you an object that can provide notifications when things change. Your Model object can also potentially handle network or disk access (alternately, you can have a separate controller that also utilizes the Model and provides network or disk access). The key here is MVC. You want to separate the model classes from the view and controller classes.