简体   繁体   中英

ARC ownership with strong and weak references

In apples example

MyViewController *myController = [[MyViewController alloc] init…];

MyViewController * __weak weakMyController = myController;
myController.completionHandler =  ^(NSInteger result) {
    MyViewController *strongMyController = weakMyController;
    if (strongMyController) {

        [strongMyController dismissViewControllerAnimated:YES completion:nil];

    }
    else {
        // Probably nothing...
    }
};

What is happening here? I'm confused about: MyViewController *strongMyController = weakMyController;

Does that mean weakMyController has a strong reference to it, so it would be like weakMyController's retain count + 1? What happens when you create a strong reference to a weak iVar?

Does that mean weakMyController has a strong reference to it, so it would be like weakMyController's retain count + 1?

The retain count for myController is the same for all the variables that have its reference. It's a value of the object, not of the variables pointing to it. And it tells the runtime ho many strong references there exist pointing to the object.

So, the line

 MyViewController *strongMyController = weakMyController;

will increment that count by 1, and ensure that as long as we have that variable in scope, that view controller won't be released.

In most cases it's enough to call methods on the weak reference inside the block ( weakMyController in your example). I think that in this case they use a strong reference because there's an animation involved (so the view controller needs to exist for the duration of the animation, which would not be guaranteed if we used a weak reference).

To respond to the other part of your question, all the strong and weak references to an object hold the same value (the memory address of the object). The difference between strong and weak is what happens when they get their values. In the case of a weak reference, the retain count stays the same, while with a strong reference it gets incremented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM