cuốn sách gpt4 ai đã làm

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

In lại Tác giả: Walker 123 更新时间:2023-11-28 18:38:30 25 4
mua khóa gpt4 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

正确的做法是什么?

谢谢,道格

câu trả lời hay nhất

你必须将 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
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress