• 十四、析构器 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

  • 相关阅读:
    部分模块
    正则表达式和re模块
    软件开发的目录规范
    模块以及模块的导入
    迭代器、可迭代对象、迭代器对象、生成器、生成器表达式和相关的面试题
    内置方法补充
    递归、二分法、匿名函数和部分内置方法
    python的闭包和装饰器
    函数名本质、函数命名空间和作用域链
    函数简介和函数的结构分析
  • 原文地址:https://www.cnblogs.com/actionke/p/4250785.html
Copyright © 2020-2023  润新知