【问题标题】:Memory Leak NSBlockOperation内存泄漏 NSBlockOperation
【发布时间】:2018-05-27 12:21:15
【问题描述】:

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

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

- (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;
}

【问题讨论】:

  • 显示EMUserInfoOperation 的实现(至少是它的初始化程序、dealloc 和任何超类方法的覆盖)以及使用从这个-loadingLocalModelOperationWithColor:gender: 方法返回的对象的代码。没有这些信息,我们无法猜测发生了什么。此外,使用 Leaks 工具模板运行应用程序并显示泄漏对象的保留/释放历史记录。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 2013-01-20
    • 2011-10-31
    • 2019-08-10
    • 2013-06-24
    • 2011-03-22
    相关资源
    最近更新 更多