gpt4 book ai didi

iphone - 释放 Objective-C block 中的对象

转载 作者:行者123 更新时间:2023-12-03 19:37:44 25 4
gpt4 key购买 nike

当使用通过完成处理程序异步返回的 Objective-C 对象(例如 AVAssetExportSession)时,这样的代码是否有任何错误:

AVAssetExportSession* exportSession = [[AVAssetExportSession alloc] initWithAsset: composition presetName: AVAssetExportPresetHighestQuality];
[exportSession exportAsynchronouslyWithCompletionHandler: ^(void) {
// export completed
NSLog(@"Export Complete %d %@", exportSession.status, exportSession.error);
[exportSession release];
}];

Instruments 将导出 session 报告为泄漏。我自己也有一些使用相同方法的类,它们也被报告为泄漏。

从我读到的所有内容来看,代码似乎应该遵循正确的内存管理规则,但必须有一些东西。我找到了this article的链接,但我不认为我造成了循环保留。

最佳答案

Objective-C 中的 block automatically take ownership范围内的对象,并且确实会导致循环引用。您的 block 隐式保留 exportSession,并且 exportSession 可能会保留您的 block 。

内存管理规则规定您应该尽快放弃对象的所有权。因此,在您的情况下,执行此操作的正确位置是在调用 exportAsynchronouslyWithCompletionHandler: 之后。

AVAssetExportSession* exportSession = [[AVAssetExportSession alloc] initWithAsset: composition presetName: AVAssetExportPresetHighestQuality];
[exportSession exportAsynchronouslyWithCompletionHandler: ^(void) {
// export completed
NSLog(@"Export Complete %d %@", exportSession.status, exportSession.error);
}];
[exportSession release];

循环引用应该是显而易见的:exportSession 将由 block 保持事件状态,并且 block 本身将由对象保持事件状态。

当你处理 block 时,我建议你使用垃圾收集环境。

关于iphone - 释放 Objective-C block 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3697861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com