9.38. Swift destructing process

发布时间 :2023-12-08 01:10:05 UTC      

The destructor is called immediately before an instance of a class is released. Use keywords deinit to mark the destructor, similar to the initialization function using the init to mark. Destructors apply only to class types.

9.38.1. Principle of destructing process #

Swift automatically releases instances that are no longer needed to release resources.

Swift handles memory management of instances through automatic reference counting (ARC).

Usually you don’t need to clean up manually when your instance is released. However, you may need to do some extra cleanup when using your own resources.

For example, if you create a custom class to open a file and write some data, you may need to close the file before the class instance is released.

9.38.2. Grammar #

In the definition of a class, there can be at most one destructor per class.The destructor takes no parameters and is written without parentheses:

deinit {
    // Execute the deconstruction process
}

9.38.3. Example #

var counter = 0;  // reference counter
class BaseClass {
    init() {
        counter += 1;
    }
    deinit {
        counter -= 1;
    }
}

var show: BaseClass? = BaseClass()
print(counter)
show = nil
print(counter)

The output of the above program execution is as follows:

1
0

When show = nil after the statement is executed, the calculator subtracts 1 show the occupied memory will be released.

var counter = 0;  // reference counter

class BaseClass {
    init() {
        counter += 1;
    }

    deinit {
        counter -= 1;
    }
}

var show: BaseClass? = BaseClass()

print(counter)
print(counter)

The output of the above program execution is as follows:

1
1

Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.