Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call deinit method within class definition in swift

Tags:

swift

deinit

I want to define a method that can destroy the instance it belongs to when a variable in this class has increased to a certain value. I attempted to do something like following:

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

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

But i would get error message saying "Expect '{' for deinitializers".

Is there anyway to self-destruct within the class?

like image 625
Joseph Zhou Avatar asked Mar 13 '23 11:03

Joseph Zhou


2 Answers

You can create a protocol which does the self destruction based on a certain criteria. Here's an example using a class

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

You can derive your class from this class and then call call() on those object. The basic idea is to have the ownership of the object at one and only one place only and then detach the ownership when the criteria is met. The ownership in this case is a static array and detaching is removing it from the array. One important thing to note is that you have to use weak reference to the object wherever you are using it.

E.g.

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")
        }
    }
}
like image 29
Pradeep K Avatar answered May 14 '23 10:05

Pradeep K


You can not call deinit method. From Apple Docs: Deinitializers are called automatically, just before instance deallocation takes place. You are not allowed to call a deinitializer yourself.

You should set that instance to nil in order to destroy that instance provided that all references to that instance are broken .

like image 198
san Avatar answered May 14 '23 10:05

san