5

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

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

 func shouldDestroySelf(){
   if calledTimes == MAX_TIMES {
     denit
   }
 } 

但我会收到错误消息说“期望'{'用于反初始化”。

反正班内有自毁吗?

4

2 回答 2

4

你不能调用deinit方法。来自苹果文档Deinitializers are called automatically, just before instance deallocation takes place. You are not allowed to call a deinitializer yourself.

您应该将该实例设置nil为以销毁该实例,前提是对该实例的所有引用都已损坏。

于 2016-01-29T05:07:09.273 回答
3

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

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)
        }
    }
}

您可以从此类派生您的类,然后在这些对象上调用 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")
        }
    }
}
于 2016-01-29T05:30:54.247 回答