An attack on the swift-------------process of destruction

Source: Internet
Author: User

destructors apply only to class types, and the destructor is called immediately before an instance of a class is disposed. Destructors deinit are labeled with keywords, similar to those used by constructors init .

Principle of the process of destruction

Swift frees up resources by automatically releasing instances that are no longer needed. As described in the Automatic Reference counting section, Swift 自动引用计数(ARC) handles the memory management of the instance. Typically, you do not need to manually clean up your instances when they are released. However, when you use your own resources, you may need to do some extra cleanup. For example, if you create a custom class to open a file and write some data, you may need to manually close the file before the class instance is freed.

In the definition of a class, each class can have at most one destructor, and the destructor takes no parameters, as follows:

deinit {    // 执行析构过程}

A destructor is called automatically before an instance release occurs. You cannot invoke the destructor on your own initiative. Subclasses inherit the destructor of the parent class, and at the end of the subclass destructor implementation, the destructor of the parent class is automatically called. The destructor of the parent class is called even if the subclass does not provide its own destructor.

Because the instance is freed until the destructor of the instance is called, the destructor can access all the properties of the instance and can modify its behavior based on those properties (such as finding a file that needs to be closed).

destructor Practice

This is an example of a destructor practice. This example describes a simple game where two new types are defined, Bank and Player , respectively. The Bank class manages a virtual coin to ensure that the number of coins in circulation is never more than 10,000. There is only one bank in the game, so the bank is implemented with classes and uses static properties and static methods to store and manage its current state.

 class 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}}      

BankUse coinsInBank properties to track the number of coins it currently owns. BankTwo methods were also provided, vendCoins(_:) and receiveCoins(_:) , respectively, were used to deal with the distribution and collection of coins.

vendCoins(_:)Method Bank Check if there are enough coins before the object distributes the coins. If the coin is not sufficient, the Bank object returns a number that is smaller than the request (if Bank there is no coin in the object, it returns 0 ). vendCoinsmethod is declared numberOfCoinsToVend as a variable parameter so that the number of coins distributed can be modified inside the method body without having to define a new variable. vendCoinsmethod returns an integer value that represents the actual number of coins provided.

receiveCoins(_:)Method simply adds Bank the number of coins received by the object back to the coin store.

PlayerClass describes a player in the game. Each player has a certain number of coins stored in their wallets at any given time. This is indicated by the player's coinsInPurse attributes:

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

Each Player instance Bank obtains a specified number of coins from the object during initialization. If there are not enough coins available, the Player instance may receive fewer coins than the specified number.

Playerclass defines a winCoins(_:) method that Bank obtains a certain number of coins from an object and adds them to the player's wallet. The Player class also implements a destructor, which Player is called before the instance is released. Here, the destructor simply returns all of the player's coins to the Bank object:

var playerOne: Player? = Player(coins: 100)print("A new player has joined the game with \(playerOne!.coinsInPurse) coins")// 打印 "A new player has joined the game with 100 coins"print("There are now \(Bank.coinsInBank) coins left in the bank")// 打印 "There are now 9900 coins left in the bank"

When an Player instance is created, Bank 100 coins are requested from the object, if enough coins are available. This Player instance is stored in a variable of the playerOne optional type named. A variable of an optional type is used here, as the player can leave the game at any time and set as optional so that you can track whether the player is currently in the game.

Because it playerOne is optional, when you access its coinsInPurse properties to print the number of coins in your wallet, use an exclamation point ( ! ) to unpack the package:

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

Here, the player has won 2,000 coins, so the player's wallet now has 2,100 coins, and the Bank object is only 7,900 coins left.

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

The player has now left the game. This is done by setting the variable of the optional type to playerOne nil represent, meaning "no Player instance". When this happens, the playerOne variable Player 's reference to the instance is broken. There is no other property or variable reference Player instance, so the instance is freed to reclaim memory. Prior to this, the instance's destructor was automatically called and the player's coin was returned to the bank.

An attack on the swift-------------process of destruction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.