gpt4 book ai didi

objective-c - 在 block 中保留可变变量而不会导致 Objective-C 中的保留循环

转载 作者:行者123 更新时间:2023-12-04 05:53:34 27 4
gpt4 key购买 nike

我正在使用块来处理非 ARC 项目中异步 http 请求的响应。代码如下(相关部分):

NSMutableUrlRequest* request = ...;
__block typeof(self) mutableSelf = self;

void (^didGetSessionBlock)(Gopher* newGopher) = ^(Gopher* newGopher) {
if (newGopher.statusCode == HTTP_OK) {
...
mutableSelf.retryOnFail = NO;
[mutableSelf executeRequest:request];
}

...
[mutableSelf setStatusCode:newGopher.statusCode];
};

Gopher* newGopher = [[[Gopher alloc] init] autorelease];

[newGopher setDidCompleteBlock:didGetSessionBlock];
[newGopher fetchSession:myApp.settings.userName password:myApp.settings.password];
__block mutableSelf使用以便我可以修改 self块内部(而不是 self 的副本)。 __block关键字,如果我理解正确,也有 mutableSelf 的作用未保留,因此在块执行时它可能已经被释放(这正是发生的情况)。

如果我改变
[mutableSelf executeRequest:request];


[self executeRequest:request];

一切都很好,因为 self被保留并且在块执行之前不会被释放。但是,直接引用 self 可能会由于保留循环而导致泄漏。

有没有解决的办法?我应该手动保留 mutableSelf什么时候声明然后在块内释放它?或者我应该使用 self在我没有修改它的块内,可能会造成泄漏?这两种变体似乎都很脆弱,需要在注释中进行解释,以避免在修改代码时出现混淆和 future 的错误。

有没有办法解决这个问题?如果没有,最好的方法是什么?

最佳答案

你不修改self在块中,您只修改它指向的对象。我认为你不需要 __block .

关于objective-c - 在 block 中保留可变变量而不会导致 Objective-C 中的保留循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9783447/

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