简体   繁体   中英

Will this closure cause a memory leak?

I know that the following causes a memory leak because MyClass and myClosure references each other.

var MyClass {
    var myVar = 0
    let myClosure: (Int) -> Void

    init() {
        self.myClosure = { x in
            self.myVar = x
        }
    }
}

Does the following cause a memory leak as well? Why or why not?

var MyClass {
    var myVar = 0

    function myFunc() {
        let myClosure = { x in
            self.myVar = x
        }

        myClosure(0)
    }
}

Nope, this will (in practise) not cause memory leaks. myClosure() is defined local inside myFunc() . When myClosure(0) gets called, the closure will be scheduled for execution, and when it's done it will be removed out of memory.

The only problem you have with your code is that self , inside your closure, is a strong reference, which might be deallocated by the time the closure is executed. This will result in a bad excess error. Make sure you create a weak reference to self, and use that in your closure.

Declare weak self to avoid memory leak and guard self in order to avoid calling deallocated self

func myFunc() {
    let myClosure = { [weak self] x in
        guard let strongSelf = self else {
            return
        }

        strongSelf.myVar = x
    }

    myClosure(0)
}

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