Memory Leak NSBlockOperation

291 views Asked by At

I declared NSBlockOperation with an object declared inside that operation. My app constantly is crashing because of memory issue. Appreciate any hint with a great explanation on this spent several hours still no success.

runtime: Memory Issues - (5 leaked types): 1 instance of NSExactBlockVariable leaked

- (EMUserInfoOperation*)loadingLocalModelOperationWithColor:(EMOutfitColor)outfitColor gender:(EMGender)gender {

__block EMUserInfoOperation* operation = [EMUserInfoOperation blockOperationWithBlock:^{
    NSURL* remoteURL = [NSURL URLWithString:self.settings[kEMRemoteUrlKey]];

    EMOutfitModel* model = nil;

    if (remoteURL == nil) {
        model = [[EMDomainDataLoader sharedLoader] loadEmbededOutfitNamed:self.name gender:gender];
    } else {
        model = [[EMDomainDataLoader sharedLoader] loadCachedOutfitNamed:self.name withVersion:self.version gender:gender];
    }
    [model syncApplyTextureFromPath:[self texturePathForColor:outfitColor] textureSampler:EMTextureSamplerColor];

    NSString *alphaPath = [self texturePathForAlpha];
    if(alphaPath.length > 0) {
        [model syncApplyTextureFromPath:alphaPath textureSampler:EMTextureSamplerAlpha];
    }

    operation.userInfo = model;
}];

return operation;
}
1

There are 1 answers

0
newacct On

I am guessing that your EMUserInfoOperation object has a strong reference to the block that the operation is created with. And this block also has a strong reference to the EMUserInfoOperation object because it captures the operation variable. So you have a retain cycle.

You can have the block only weakly reference the EMUserInfoOperation object by doing the following:

EMUserInfoOperation* operation;
__block __weak typeof(operation) weakOperation;
weakOperation = operation = [EMUserInfoOperation blockOperationWithBlock:^{
    typeof(operation) strongOperation = weakOperation;
    if (strongOperation) {

        // ...

        strongOperation.userInfo = model;
    }
}];
return operation;