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

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


我用一个块初始化属性。在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作为参数提供给块:

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

thing.setup = ^(Thing *localThing) {

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

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

10-13 06:30