문제

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!

도움이 되었습니까?

해결책 2

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.

다른 팁

It's reasonable to have each view controller retain the object while they are working on it.

While view controller A is working with the object, it retains it. When it is finished and will pass it to B, B retains it, and then A sets its own reference to it to nil to resign ownership of it. This process continues until the final view controller commits the object, then sets its own reference to it to nil, which should cause the object to be deallocated.

once committed , you just set the object to nil. ARC will automatically release it.

You can override dealloc method in your view controllers and set the objects to nil there. So that, when the instance of your view controller goes out of scope, the dealloc is called and objects will set to nil. Do not call [super dealloc] .

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top