swift4.03 学习笔记(15)

Deinitialization

一个类的实例被释放之前调用deinitializer(反初始化器)
反初始化器只能在类类型中使用

反初始化器的机制

当你的实例不再被使用的时候,Swift会自动释放你的实例,以释放资源。

Swift通过automatic reference counting (ARC)(引用自动计数)处理实例的内存管理。因此,不用手动的释放实例,但是实例使用的资源,比如文件,连接什么的需要实例释放之前自己手动关闭。

反初始化器的语法:

deinit {
    // perform the deinitialization
}

反初始化器在内存释放之前自动调用,不能手动调用。

父类的反初始化器会被子类继承,如果子类实现了反初始化器,那么在子类的反初始化器的结尾会自动调用父类的反初始化器。如果子类没有实现发初始化器,子类会默认继承父类的反初始化器。

由于反初始化器是在实例释放之前才调用,因此,反初始化器可以访问实例所有的属性,并修改它们。

反初始化器的使用

定义一个Bank类,Bank类中的一个类型属性coinsInBank表示该银行有10000元,类型方法distribute(coins:)从银行取钱,类型方法receive(coins:)往银行存钱。

class Bank {
    static var coinsInBank = 10_000
    static func distribute(coins numberOfCoinsRequested: Int) -> Int {
        let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank)
        coinsInBank -= numberOfCoinsToVend
        return numberOfCoinsToVend
    }
    static func receive(coins: Int) {
        coinsInBank += coins
    }
}

定义Player类,Player类初始化时从银行取钱,win时从银行取现,调用反初始化器时把所有取到的钱返回给银行。

class Player {
    var coinsInPurse: Int
    init(coins: Int) {
        coinsInPurse = Bank.distribute(coins: coins)
    }
    func win(coins: Int) {
        coinsInPurse += Bank.distribute(coins: coins)
    }
    deinit {
        Bank.receive(coins: coinsInPurse)
    }
}

初始化Player,从银行取100, 银行剩下9900

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"

playerOne从银行赢2000,现在银行剩下7900。

playerOne!.win(coins: 2_000)
print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins")
// Prints "PlayerOne won 2000 coins & now has 2100 coins"
print("The bank now only has \(Bank.coinsInBank) coins left")
// Prints "The bank now only has 7900 coins left"

playerOne设为nil时,Swift自动释放playerOne实例,但在释放之前调用playerOne的反初始化器,把得到的所有钱返回给银行,银行的钱又成为10000。

playerOne = nil
print("PlayerOne has left the game")
// Prints "PlayerOne has left the game"
print("The bank now has \(Bank.coinsInBank) coins")
// Prints "The bank now has 10000 coins"

你可能感兴趣的:(swift4.03 学习笔记(15))