Search code examples
iosswiftpointersweak-references

Problems with weak var and pointers between two classes


I'm using Swift language. I'm in my viewcontroller class, and I want to store something on another class, but I don't want that class to have any strong pointers to my class. So i'm using weak. I'm trying two ways to do this. One works (as in succeeds at not have a strong pointer to my viewcontroller class), and one doesn't (The pointer to my viewcontroller is strong, even though I name it as weak.

class MyViewController {

    override func viewDidLoad() {
    someOtherClass.function(someArgument) { [ weak myself = self ] in
    myself?.someButton.text = "I got you captured, Mr. ViewController"
}

The previous code succeeds in not letting someOtherClass point strongly to MyViewController. Then I take out the weak myself = self and name it in the function itself, like this:

class MyViewController {

override func viewDidLoad() {
    someOtherClass.function(someArgument) {
    weak let myself = self
    myself?.someButton.text = "I got you captured, Mr. ViewController"
}

In this instance, someOtherClass points strongly to my viewController class. Anyone know why?

}


Solution

  • It's all about scope of variable creation. In your first example you are making a new variable (weak myself) in the scope of the ViewController class. Then you pass that weak variable into the new class's function and do whatever you would like.

    In your second example you are creating a new variable (weak myself) inside the function in the scope of the new class. Since you create that variable in the new class using a strong referenced self you have a strong reference to your ViewController inside the new class.