Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 859
Awesome-o Avatar asked Feb 06 '26 14:02

Awesome-o


1 Answers

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");
    };
}
like image 62
CrimsonChris Avatar answered Feb 09 '26 12:02

CrimsonChris