Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strongify and weakify causing issues

I have a code that does something like this:

@weakify(self);
dispatch_group_notify(myGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    @strongify(self);
    [self doSomething];
});

However, the "self" seems to be actually nil inside of this block. i didn't even know this was possible. I thought that the @weakify virtually creates a weak reference to self, lets call this __weakSelf. then when i use @strongify, it assigns a local variable to __weakSelf.

why is self nil at the line [self doSomething] ?? does this mean that self already got released because dispatch_group_notify isn't held on to by self or something?? and thus self gets dealloc'ed at any time? (such as when my block is actually run)?

like image 465
David T. Avatar asked Apr 18 '26 06:04

David T.


1 Answers

You ask:

why is self nil at the line [self doSomething] ??

Because it was nil before it got to the @strongify(self) line. I.e. it was deallocated before the notify block even started.

does this mean that self already got released because dispatch_group_notify isn't held on to by self or something??

Yep. Or, more accurately, self was already released by the time the block specified by dispatch_group_notify was invoked.

That's the whole purpose of the weakify: Make sure that the occurrences of self inside the block of dispatch_group_notify don't result in self being retained. The purpose of the strongify inside the block is if self is not released yet, make sure it isn't released while the block runs, but if it's released after weakify, but before you reach the strongify line, then go ahead and let it get deallocated and let self be nil.

--

A typical use-case is when one initiates a bunch of async requests and have a notify block that updates the UI when the downloads are done. You might use weakify to the reference to the view controller, so if you dismiss the view controller before the downloads are done, the notify block won't hang on to it (which makes sense, if the user dismisses the view controller, there's no point in hanging on to a view controller reference to update a view that is no longer present). But you might use strongify inside that block so that if the view controller wasn't dismissed before the notify block started, make sure it isn't released while the notify block is running (this is often a less critical issue, but sometimes is important).

like image 199
Rob Avatar answered Apr 20 '26 11:04

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!