2016-01-29 209 views
1

我想定義一個方法,當該類中的變量已增加到某個特定值時,它可以銷燬它所屬的實例。我試圖做如下事情:如何在swift的類定義中調用deinit方法

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

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

但我會得到錯誤消息說'期望'{'爲deinitializers「。

反正有沒有在課堂內自我毀滅?

+0

它內置作爲弧的一部分。 self.deinit將銷燬一個對象。但只要確保它不是一個當前顯示的viewController,因爲這可能會導致問題。 – NSGangster

+0

我想你可能指的是[這個線程](http://stackoverflow.com/questions/26091862/how-to-call-deinit-in-swift)? – bipartite

+0

hi Matthew self.deinit不允許在類定義中調用。 –

回答

1

您可以創建一個基於特定標準進行自我銷燬的協議。下面是使用類的示例

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()。基本思想是僅在一個地方擁有對象的所有權,然後在滿足標準時拆除所有權。在這種情況下,所有權是一個靜態數組,而分離將其從數組中移除。需要注意的一件重要事情是,無論使用哪個對象,都必須使用弱引用。

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") 
     } 
    } 
} 
+0

這真的很聰明的人!哇。它讓我想起了一個古老的說法,即任何工程問題都可以通過增加一層來解決 –

1

您不能撥打deinit方法。來自Apple DocsDeinitializers are called automatically, just before instance deallocation takes place. You are not allowed to call a deinitializer yourself.

如果銷燬該實例,只要所有對該實例的引用都被破壞,就應該將該實例設置爲nil

相關問題