首页 > 解决方案 > 内存泄漏 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;
}

标签: objective-cxcodememoryretain-cyclensblockoperation

解决方案


我猜你的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;

推荐阅读