快速的方法数组,无需参考周期 [英] Array of methods in swift without reference cycle

查看:97
本文介绍了快速的方法数组,无需参考周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是创建一个包含数组的类。数组的元素将是同一类的方法。像这样:

My goal is to create a class which contains an array. The elements of the array will be the methods of the same class. like:

class MyClass {
    lazy var functions = [self.myFirstMethod, self.mySecondMethod]

    deinit {
        print("Deinit")
    }

    func myFirstMethod() {
        // Do Something
    }

    func mySecondMethod() {
        // Do Something
    }

    func executeAll() {
        for f in functions {
            f()
        }
    }
}

当我呼叫 executeAll()正常工作,我达到了预期的结果:

When I call the executeAll() it works fine and I achieve my expected result:

var myObject = MyClass()
myObject.executeAll()

问题是,它创建了引用周期。 MyClass 的实例保存数组 functions functions 数组自我。因此,如果我编写以下代码:

The problem is, it create reference cycle. Instance of MyClass holds the array functions and functions array holds self. So If I write below code:

var myObject: MyClass? = MyClass()
myObject.executeAll()
myObject = nil

它由于这个强大的参考周期,因此不会调用 deinit 方法。
如何将方法指针作为弱自我添加到数组?我不想在 executeAll 方法中使用函数的本地副本。

It will not call deinit method because of this strong reference cycle. How can I add method pointers to array as weak self? I don't want to use a local copy of functions in executeAll method.

推荐答案

如果方法列表独立于特定实例,则可以将其设为 type属性,并避免引用循环:

If the method list is independent of the particular instance then you can make it a type property and avoid the reference cycle:

class MyClass {
    static let functions = [myFirstMethod, mySecondMethod]

    func executeAll() {
        for f in MyClass.functions {
            f(self)()
        }
    }

   // ...
}

数组元素是咖喱函数类型

The array elements are "curried functions" of the type

(MyClass) -> () -> ()

比较实例方法是Swift中的已固化函数

这篇关于快速的方法数组,无需参考周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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