Search code examples
objective-ciosmemory-managementnsoperationtarget-action

Handling target/action weak reference with NSOperation


I'm using a NSOperation to handle background processing in an iOS app, and I'm trying to understand the target/action pattern. In the delegate pattern, the delegate is held as a weak reference, and the delegate object is responsible for setting the other object's delegate field to nil before it deallocs. In the target/action pattern, as I understand it, the target is held as a weak reference, for similar reasons. However, it doesn't seem as easy to "nil out" the target field when the target object deallocs, and with NSOperations there is a chance the operation could still be sitting on a queue when its target is deallocated.

How should memory management be handled in this case (of a NSOperation performing background processing, then using target/action to return a value to the creator of the NSOperation)?


Solution

  • As explained in The Target, it's up to you to make sure that the target is available if a control might send an action. In practice, this isn't a problem because the target is usually a controller that's created before and deallocated after the controls.

    If you're sending action messages from an operation, you'll need to ensure that the target isn't deallocated until after the operation completes. One way to do that might be to have the target retain itself until the operation completes.

    Another approach might be to use an intermediate object that's known to both the operation and the target. The operation could treat the intermediate object like a proxy for the target and send the action to it rather than sending it directly to the target, and the target could update the intermediate appropriately if it's deallocated. Both the target and the operation could retain the intermediate without creating a retain cycle. I'm not sure this method would be my first choice -- seems a little overcomplicated -- but it might help.