内存泄漏NSBlockOperation

时间:2018-05-27 12:21:16

标签: objective-c xcode memory retain-cycle nsblockoperation

我使用在该操作中声明的对象声明了NSBlockOperation。由于内存问题,我的应用程序不断崩溃。感谢任何提示都有一个很好的解释,花了几个小时仍然没有成功。

  

运行时:内存问题 - (5个泄漏类型):1个 NSExactBlockVariable 实例泄露

- (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 个答案:

答案 0 :(得分:0)

我猜你的EMUserInfoOperation对象强烈引用了创建操作的块。此块也强烈引用EMUserInfoOperation对象,因为它捕获operation变量。所以你有一个保留周期。

您可以通过执行以下操作让块仅弱引用EMUserInfoOperation对象:

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

        // ...

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