我有一个对象,其属性指向一个 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);
Tôi là một lập trình viên xuất sắc, rất giỏi!