首页 > 代码库 > 十四、析构器 Deinitialization
十四、析构器 Deinitialization
1. 当一个实例被释放(deallocated)时,析构器会立即被调用。使用关键字 deinit
来定义析构器。只有类类型才有析构器。
2. 析构器工作原理 How Deinitialization Works
当一个实例的自动引用计数 Automatic Reference Counting 为0时,Swift会释放这个实例。一般情况下,当一个实例被dealloc时,释放资源的工作都有Swift完成,但是某些时候,你需要自己进行一些释放资源的工作,比如你创建一个类执行打开文件操作,并写数据到文件中,在实例被dealloc时,你需要关闭文件。
deinit { // perform the deinitialization }
析构器是编译器自动调用的,你不能手动调用。父类的析构器会被子类继承,当子类的析构器被调用时,父类的析构器会自动被调用。即使子类没有提供自己的析构器,父类的析构器也会被调用。
析构器可以访问调用它的实例的所有属性和方法。
例子:
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) } }
var playerOne: Player? = Player(coins: 100) println("A new player has joined the game with \(playerOne!.coinsInPurse) coins") // prints "A new player has joined the game with 100 coins" println("There are now \(Bank.coinsInBank) coins left in the bank") // prints "There are now 9900 coins left in the bank"
playerOne!.winCoins(2_000) println("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins") // prints "PlayerOne won 2000 coins & now has 2100 coins" println("The bank now only has \(Bank.coinsInBank) coins left") // prints "The bank now only has 7900 coins left"
playerOne = nil println("PlayerOne has left the game") // prints "PlayerOne has left the game" println("The bank now has \(Bank.coinsInBank) coins") // prints "The bank now has 10000 coins"
参考:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Deinitialization.html#//apple_ref/doc/uid/TP40014097-CH19-ID142
十四、析构器 Deinitialization
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。