[Swift]闭包带来循环引用无法释放

如下定义Student,在构造函数传入闭包。假设这个类是已经存在的,调用方无法修改;那调用时应该注意避免循环引用

class Student{
        private var doWork:(()->())
        
        init(delegate:  @escaping (()->())){
            self.doWork = delegate
        }
        
        deinit {
            print("deinit student")
        }
    }

Teacher内部持有Student,如果Student的构造函数需要的闭包直接指向Teacher的成员方法,会发生循环引用

不应该写为

myStudent = Student(delegate:classBegin)

需要把classBegin放到一个weak self的闭包中被呼叫才能避免循环引用

class Teacher{
        private func classBegin() {
            print("hi, classmates!")
        }
        
        private var myStudent : Student?
        
        func addStudent() {
            
            //这样写无法释放,会内存泄露
            //myStudent = Student(delegate:classBegin)
            
             myStudent = Student(delegate: {
                [weak self] in
                self?.classBegin()
             })
        }
        
        deinit {
            print("deinit teacher")
        }
    }

你可能感兴趣的:([Swift]闭包带来循环引用无法释放)