how to call deinit method within class definition in swift

Joseph Zhou picture Joseph Zhou · Jan 29, 2016 · Viewed 10k times · Source

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?

Answer

san picture san · Jan 29, 2016

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 .