How do I avoid capturing self in blocks when implementing an API?

I have a working app and I’m working on converting it to ARC in Xcode 4.2. One of the pre-check warnings involves capturing self strongly in a block leading to a retain cycle. I’ve made a simple code sample to illustrate the issue. I believe I understand what this means but I’m not sure the “correct” or recommended way to implement this type of scenario.

  • self is an instance of class MyAPI
  • the code below is simplified to show only the interactions with the objects and blocks relevant to my question
  • assume that MyAPI gets data from a remote source and MyDataProcessor works on that data and produces an output
  • the processor is configured with blocks to communicate progress & state

code sample:

// code sample
self.delegate = aDelegate;

self.dataProcessor = [[MyDataProcessor alloc] init];

self.dataProcessor.progress = ^(CGFloat percentComplete) {
    [self.delegate myAPI:self isProcessingWithProgress:percentComplete];
};

self.dataProcessor.completion = ^{
    [self.delegate myAPIDidFinish:self];
    self.dataProcessor = nil;
};

// start the processor - processing happens asynchronously and the processor is released in the completion block
[self.dataProcessor startProcessing];

Question: what am I doing “wrong” and/or how should this be modified to conform to ARC conventions?

8 Answers
8

Leave a Comment