0

Without too much judgement as to the design of this code, I am wondering how to work around the retain cycle I've created...

@interface BlockClass : NSObject
{
    id actualObject;
    NSError *actualError;
    void (^block)(id, NSError *);
}
@end

@implementation BlockClass

- (id)init
{
    self = [super init];

    if (self) {
        block = ^(id object, NSError *error){
            actualObject = object; // Compiler warns: capturing 'self' strongly in this block is likely lead to a retain cycle
            actualError  = error;
        };
    }

    return self;
}

1 Answer 1

0

The problem is that you're retaining the block by assigning it to an ivar, and since the block assigns to an ivar, it needs to retain self--hence the retain cycle.

You could have equivalent behavior by returning the block from an instance method:

@interface BlockClass : NSObject
{
    id actualObject;
    NSError *actualError;
}
@end

@implementation BlockClass

- (id)init
{
    self = [super init];

    if (self) {
    }

    return self;
}

-(void (^)(id, NSError *))block {
    return ^(id object, NSError *error){
        actualObject = object;
        actualError  = error;
    };
}

@end

This avoids the retain cycle because the block returned is released as soon as it's executed.

1
  • Yep. This definitely all makes sense. Thank you.
    – edelaney05
    May 6, 2012 at 19:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.