如何在 swift 中的类定义中调用 deinit 方法

Jos*_*hou 6 swift deinit

我想定义一个方法,当该类中的变量增加到某个值时,该方法可以销毁它所属的实例。我尝试做类似以下的事情:

 var calledTimes = 0 //some other method would update this value

 func shouldDestroySelf(){
   if calledTimes == MAX_TIMES {
     denit
   }
 } 
Run Code Online (Sandbox Code Playgroud)

但我会收到错误消息“Expect '{' for deinitializers”。

班级里有没有自毁的事情?

Pra*_*p K 4

您可以创建一个协议,根据一定的标准进行自我销毁。这是一个使用类的示例

class SelfDestructorClass
{
    var calledTimes = 0
    let MAX_TIMES=5
    static var instancesOfSelf = [SelfDestructorClass]()

    init()
    {
        SelfDestructorClass.instancesOfSelf.append(self)
    }

    class func destroySelf(object:SelfDestructorClass)
    {
        instancesOfSelf = instancesOfSelf.filter {
            $0 !== object
        }
    }

    deinit {
        print("Destroying instance of SelfDestructorClass")
    }

    func call() {
        calledTimes += 1
        print("called \(calledTimes)")
        if calledTimes > MAX_TIMES {
            SelfDestructorClass.destroySelf(self)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以从此类派生您的类,然后对这些对象调用 call() 。基本思想是仅在一处拥有对象的所有权,然后在满足条件时分离所有权。在这种情况下,所有权是一个静态数组,分离是将其从数组中删除。需要注意的一件重要事情是,无论您在哪里使用对象,都必须使用对该对象的弱引用。

例如

class ViewController: UIViewController {

    weak var selfDestructingObject = SelfDestructorClass()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func countDown(sender:AnyObject?)
    {
        if selfDestructingObject != nil {
            selfDestructingObject!.call()
        } else {
            print("object no longer exists")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)