سؤال

I'm aware of the fact that you should use weakSelf in block that may survive yourself to avoid retain memory cycle. like:

__weak id weakSelf = self;
self.block = ^{
    [weakSelf something];
}

But I'm trying to find a generic way. I could use a macro like:

#define Weakify(o) __weak __typeof__((__typeof__(o))o)
#define WeakifySelf(o) Weakify(self) o = self;

WeakifySelf(weakSelf)
self.block = ^{
    [weakSelf something];
}

Which simplify, but I wonder why I can't use an ivar on my viewController.

@interface YDViewController : UIViewController
{
    __weak id _weakSelf;
}

and then use this iVar

self.block = ^{
    [_weakSelf something];
}

Any idea?

هل كانت مفيدة؟

المحلول

The issue that sinks this idea is that [_weakSelf something] is, under the hood, exactly the same as [self->_weakSelf something].

So even though you're trying to use a weak reference, you end up using the strong reference to get to the weak reference and capturing both.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top