反初始化(Deinitialization)
反初始化概念:
Swift里面有自动内存管理机制(ARC),当你的实例被销毁的时候自动帮你清理内存。但是有时候你想要手动释放内存,想要在内存释放之前做一些操作,如:当你的自定义的类的一个实例打开一个文件写入数据的时候,你需要在这个实例销毁(deallocated)之前将文件关闭这时候就需要反初始化(Deinitialization)。与初始化不同,每个类最多有一个反初始化方法。反初始化的关键字是deinit,反初始化的格式如下:
deinit {
// perform the deinitialization
}```
#####反初始化举例:
定义一个Bank 类,再定义一个有deinit 方法的Player 类,当每个Player 实例消亡之前都会执行Player 的deinit 方法。
//Bank 类
class Bank {
static var coinsInBank = 10_000
static func vendCoins(numberOfCoinsRequested: Int) -> Int {
let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank)
coinsInBank -= numberOfCoinsToVend
return numberOfCoinsToVend
}
static func receiveCoins(coins: Int) {
coinsInBank += coins
}
}
//Player 类
class Player {
var coinsInPurse: Int
init(coins: Int) {
coinsInPurse = Bank.vendCoins(coins)
}
func winCoins(coins: Int) {
coinsInPurse += Bank.vendCoins(coins)
}
deinit {
Bank.receiveCoins(coinsInPurse)//实例销毁之前执行这里
}
}
var playerOne: Player? = Player(coins: 100)
print("A new player has joined the game with (playerOne!.coinsInPurse) coins")
// Prints "A new player has joined the game with 100 coins"
print("There are now (Bank.coinsInBank) coins left in the bank")
// Prints "There are now 9900 coins left in the bank"```