gpt4 book ai didi

ios - block 内不允许解除对 __weak 指针的引用

转载 作者:技术小花猫 更新时间:2023-10-29 10:59:59 26 4
gpt4 key购买 nike

Apple docs假设我可以通过捕获对 self 的弱引用来避免强引用循环,如下所示:

- (void)configureBlock {
XYZBlockKeeper * __weak weakSelf = self;
self.block = ^{
[weakSelf doSomething]; // capture the weak reference
// to avoid the reference cycle
}
}

然而当我写这段代码时,编译器告诉我:

Dereferencing a __weak pointer is not allowed due to possible null value caused by race condition, assign it to strong variable first

然而,下面的代码不会创建一个强引用循环,并可能泄漏内存吗?

- (void)configureBlock {
XYZBlockKeeper *strongSelf = self;
self.block = ^{
[strongSelf doSomething];
}
}

最佳答案

你应该像这样使用:例如:

__weak XYZBlockKeeper *weakSelf = self;

self.block = ^{

XYZBlockKeeper *strongSelf = weakSelf;

if (strongSelf) {
[strongSelf doSomething];
} else {
// Bummer. <self> dealloc before we could run this code.
}
}

关于ios - block 内不允许解除对 __weak 指针的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17824459/

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