简体   繁体   English

我应该什么时候使用 deinit?

[英]When should I use deinit?

我在阅读The Swift Programming Language guide时遇到了一个名为deinit()的函数,但我仍然想知道为什么以及何时需要实现它,因为我们实际上并不需要管理内存。

It's not required that you implement that method, but you can use it if you need to do some action or cleanup before deallocating the object.不需要您实现该方法,但如果您需要在释放对象之前执行某些操作或清理,则可以使用它。

The Apple docs include an example: Apple 文档包括一个示例:

struct Bank {
    static var coinsInBank = 10_000
    static func vendCoins(var numberOfCoinsToVend: Int) -> Int {
        numberOfCoinsToVend = min(numberOfCoinsToVend, coinsInBank)
        coinsInBank -= numberOfCoinsToVend
        return numberOfCoinsToVend
    }
    static func receiveCoins(coins: Int) {
        coinsInBank += coins
    }
}

class Player {
    var coinsInPurse: Int
    init(coins: Int) {
        coinsInPurse = Bank.vendCoins(coins)
    }
    func winCoins(coins: Int) {
        coinsInPurse += Bank.vendCoins(coins)
    }
    deinit {
        Bank.receiveCoins(coinsInPurse)
    }
}

So whenever the player is removed from the game, its coins are returned to the bank.因此,每当玩家被从游戏中移除时,其硬币就会返还给银行。

A deinit() is called immediately before a class instance is deallocated, and it is helpful when you are working with your own resources.在释放类实例之前立即调用deinit() ,这在您使用自己的资源时很有帮助。 For example, if you create a custom class to open a file and write some data to it, you might need close the file before the class instance is deallocated.例如,如果您创建一个自定义类来打开一个文件并向其中写入一些数据,您可能需要在释放类实例之前关闭该文件。 The most important thing to remember is a class definition can have at most one deinit() per class要记住的最重要的事情是一个类定义每个类最多可以有一个deinit()

从 iOS9 开始,removeObserver 被自动调用。

如果您的类管理文件句柄或不同的资源,您可以在 deinit 中关闭该句柄,以确保在释放对象后它不会继续存在。

A deinitializer is called immediately before a class instance is deallocated.在释放类实例之前立即调用析构器。 You write deinitializers with the deinit keyword, similar to how initializers are written with the init keyword.使用 deinit 关键字编写析构器,类似于使用 init 关键字编写初始化器的方式。 Deinitializers are only available on class types.Class definitions can have at most one deinitializer per class.析构器仅适用于类类型。类定义每个类最多可以有一个析构器。 The deinitializer does not take any parameters and is written without parentheses.析构器不接受任何参数,并且不带括号。 I used deinit to removeObserver of notification from the application,as given below.我使用 deinit 从应用程序中删除通知的观察者,如下所示。

deinit {
    NotificationCenter.default.removeObserver(self, name: 
    NSNotification.Name(rawValue: "gotoLogin"), object: nil)
    NotificationCenter.default.removeObserver(self, name: 
    NSNotification.Name(rawValue: "gotoMain"), object: nil)
    NotificationCenter.default.removeObserver(self, name: 
    NSNotification.Name(rawValue: "gotoRegister"), object: 
    nil)
    NotificationCenter.default.removeObserver(self, name: 
    NSNotification.Name(rawValue: "gotoBook"), object: nil)
    NotificationCenter.default.removeObserver(self, name: 
    NSNotification.Name(rawValue: "gotoCurrentMainMenu"), 
    object: nil)
    NotificationCenter.default.removeObserver(self, name: 
    NSNotification.Name(rawValue: "gotoEventMenu"), 
    object: nil)
}

如果您在某个需要按照您的节奏释放的对象中创建大量操作,您可以在deinit执行此deinit

The "best answer" should now look more like this “最佳答案”现在应该看起来更像这样

I was not able to edit it我无法编辑它

 struct Bank {
static var coinsInBank = 10000
static func vendCoins(money numberOfCoinsToVend: Int) -> Int {
    let CoinsToVend = min(numberOfCoinsToVend, coinsInBank)
    coinsInBank -= CoinsToVend
    return CoinsToVend
}
static func receiveCoins(coins: Int) {
    coinsInBank += coins
}
}

class Player {
var coinsInPurse: Int
init(coins: Int) {
    coinsInPurse = Bank.vendCoins(money:coins)
}
func winCoins(coins: Int) {
    coinsInPurse += Bank.vendCoins(money:coins)
}
deinit {
    Bank.receiveCoins(coins:coinsInPurse)
}
}



print("Balance in Account: \(Bank.coinsInBank)")

 var Player1: Player? = Player(coins: 9000)



  print("Requested Amount to Withdraw: \(Player1!.coinsInPurse)")

  print("Balance After Withdraw: \(Bank.coinsInBank)")

 Player1 = nil

 print("Balance in Account: \(Bank.coinsInBank)")

And output should look like this输出应该是这样的

Balance in Account: 10000 Requested Amount to Withdraw: 9000 Balance After Withdraw: 1000 Balance in Account: 10000账户余额:10000 请求提款金额:9000 提款后余额:1000 账户余额:10000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM