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

后端 未结 3 897
没有蜡笔的小新
没有蜡笔的小新 2021-01-29 21:17

I\'m starting to integrate libextobjc (https://github.com/jspahrsummers/libextobjc) into my iOS application primarily to take advantage of EXTScope\'s @strongify an

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-29 21:32

    How @strongify works

    After @strongify is called, self will have a different pointer address inside the block than it will outside the block. That's because @strongify declares a new local variable called self each time. (This is why it suppresses the -Wshadow warning, which will “warn whenever a local variable shadows another local variable.”) It's worth reading and understanding the implementation of these functions. So even though the names are the same, treat them as separate strong references.

    Using @strongify in your code

    Presupposing (which is not true) that each use of a block would create a reference cycle, you could:

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

    However, remember that after your first use of @strongify, self will refer to local, stack variables. These will typically get destroyed when the scope in which they're defined ends (as long as you aren't storing them to properties or using them in a nested block). So based on the code you showed, you only need it after // self reference #1.

    See Also

    Reading the unit test covering @weakify and @strongify will help clarify the correct usage of these functions.

提交回复
热议问题