EzDevInfo.com

libextobjc

A Cocoa library to extend the Objective-C programming language.

Explanation of how weakify and strongify work in ReactiveCocoa / libextobjc

I understand that you should use @weakify @strongify to avoid retain cycles but I don't completely understand how they actually achieve this?


Source: (StackOverflow)

iOS Proper Use of @weakify(self) and @strongify(self)

I'm starting to integrate libextobjc (https://github.com/jspahrsummers/libextobjc) into my iOS application primarily to take advantage of EXTScope's @strongify and @weakify, but have a few questions before proceeding too deep into the process.

Here's an example that's intentionally overly-complicated to try to suss out how to handle this:

- (void)someMethod {
    if (self.someBOOL) {
        _someObjectInstanceVar = [Object objectWithCompletionHandler:^{
            // self reference #1
            if (self.someProperty) {
                // self reference #2
                [[Async HTTPRequest] sendAWithID:self.property.id completionHandler:^(void (^)(NewObject *newObject) {
                    // self reference #3
                    [self showViewWithObject:newObject handler:^{
                        // self reference #4
                        [self reloadData];
                    }];
                }];
            }
        }];

    else {
        [[Async HTTPRequest] sendBWithID:self.property.id completionHandler:^{
            // self reference #5
            [self reloadData];
        }];
    }
}

My understanding is that if I want to do anything like an async HTTP request, and inside the completion handler reference self, like [self reloadData], I don't need to do anything with strong/weak as the request block itself isn't retaining the completion block, so there's no problems with retain cycles there. In the above code example, I think #5 is a case where a retain cycles isn't an issue.

The main concern are all of the objects that take a block as a property/init param, that are internally holding onto the block properties. Inside the objectWithCompletionHandler method, where someObject holds onto the completionHandler block as an instance variable, there are multiple references to self there that I do know would cause a leak. My main question is in such a case, how would you need to handle weakify and strongify to make it "safer"? Would one @weakify and @strongify call each be sufficient, like the following:

- (void)someMethod {
    @weakify (self);

    _someObjectInstanceVar = [Object objectWithCompletionHandler:^{
        @strongify(self);
    ...
}

Would the above @strongify(self) reference be sufficient to use for self references #1, 2, 3, and 4, or do I have to (and would it even work) get a new weak/strong reference to use inside the sendAWithID method and the nested reloadData?

EDIT: Fixed code to have question make more sense and fix some syntax errors.


Source: (StackOverflow)

Advertisements