gpt4 book ai didi

iOS block 。如何从 block setter 中引用对象实例?

转载 作者:行者123 更新时间:2023-11-28 18:38:30 25 4
gpt4 key购买 nike

我有一个对象,其属性指向一个 block :

typedef void (^ThingSetter)();
@property(nonatomic, strong) ThingSetter setup;

我用 block 初始化属性。在 block 中,我引用了对象实例:

Thing *thing = [[Thing alloc] init];

thing.setup = ^() {

plainOleCFunction(thing.number);
[thing doSomethingWithString:@"foobar"];
};

但是我收到关于保留循环的编译警告:

capturing 'thing' strongly in this block is likely to lead to a retain cycle
block will be retained by the captured object

正确的做法是什么?

谢谢,道格

最佳答案

你必须将 thing 指定为弱引用:

Thing *thing = [[Thing alloc] init];
__weak Thing *weakThing = thing;

thing.setup = ^() {

plainOleCFunction(weakThing.number);
[weakThing doSomethingWithString:@"foobar"];
};

或者您可以提供 thing 作为 block 的参数:

Thing *thing = [[Thing alloc] init];

thing.setup = ^(Thing *localThing) {

plainOleCFunction(localThing.number);
[localThing doSomethingWithString:@"foobar"];
};
thing.setup(thing);

关于iOS block 。如何从 block setter 中引用对象实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14788756/

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