避免在Swift中为函数指针保留循环 [英] Avoid retain cycles for function pointers in Swift

查看:79
本文介绍了避免在Swift中为函数指针保留循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们从这个游乐场示例开始

示例1

import UIKit

internal final class TestClass1 {
    var testVar: Int = 1

    internal init() {
        print("TestClass1 init is called!")
    }

    deinit {
        print("TestClass1 deinit is called!")
    }

    internal func func1() {
        print("func1 is called!")
    }
}

internal final class TestClass2 {
    init() {
        let testClass1: TestClass1 = TestClass1()
        testClass1.testVar = 10
    }
}

var testClass2: TestClass2 = TestClass2()

输出

TestClass1初始化被调用!

TestClass1 init is called!

TestClass1 deinit被调用!

TestClass1 deinit is called!

示例2

import UIKit

internal final class TestClass1 {
    internal final var funcPointer: (() -> ())!

    internal init() {
        self.funcPointer = self.func1
        print("TestClass1 init is called!")
    }

    deinit {
        print("TestClass1 deinit is called!")
    }

    internal func func1() {
        print("func1 is called!")
    }
}

internal final class TestClass2 {
    init() {
        let testClass1: TestClass1 = TestClass1()
        testClass1.funcPointer()
    }
}

var testClass2: TestClass2 = TestClass2()

输出

TestClass1初始化被调用!

TestClass1 init is called!

func1被调用!

我的问题是,示例2中从未调用deinit()方法.我认为有一个保留周期,但我不知道如何解决它.

My problem is, that the deinit() method is never called in example 2. I think there is a retain cycle but I don't know how to fix it.

我找到了这个示例,所以发布,但是我无法在示例代码中实现它.

I found this example and this SO post but I can't implement it in my example code.

推荐答案

要解决此问题,您必须通过弱自我调用func1.

To fix it, you have to call the func1 through weak self.

internal init() {
    self.funcPointer = { [weak self] in
        self?.func1()
    }
    print("TestClass1 init is called!")
}

这样,您可以防止保留周期.

This way you can prevent retain cycles.

此刻发生的事情是,您正在为实例属性分配一个实例函数,而该实例属性现在对您的函数有很强的引用.

What happens at the moment is that you are assigning an instance function to your instance property who now has a strong reference to your function.

希望这会有所帮助.

这篇关于避免在Swift中为函数指针保留循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆