Awesome-o Awesome-o - 4 months ago 50
Objective-C Question

Objective-C macro with weak self

I have a macro that performs an awesome log. However, it can't be used from within a block owned by

self
because it will form a retain cycle.

The awesome log:

#define AWESOME_LOG(__FORMAT__, ...) ALog((@"%p %s:%d " __FORMAT__), self, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)


The not so awesome retain cycle:

- (void)someMethod:(BOOL)awesome
{
self.dumbBlock = ^{
AWESOME_LOG(@"Is this awesome? %@", awesome ? @"Yes" : @"No");
};
}


Is there any preprocessor voodoo that can ensure that
self
is weakly referenced here?

Answer

Try using @weakify/@strongify. It creates a new weak/strong reference that shadows self.

http://blog.aceontech.com/post/111694918560/weakifyself-a-more-elegant-solution-to

- (void)someMethod:(BOOL)awesome {
    @weakify(self);
    self.dumbBlock = ^{
        @strongify(self);
        AWESOME_LOG(@"Is this awesome? %@", awesome ? @"Yes" : @"No");
    };
}