Latest web development tutorials

Swift destructor process

Before an instance of a class is released, the destructor is called immediately. Use keywords deinit to mark the destructor, use similar initialization function init to mark. Destructors applies only to class types.


Destructor process principle

Swift will automatically release the instance is no longer needed to free up resources.

Swift by Automatic Reference Counting (ARC) handles memory management instances.

Usually when you do not need to manually instance is released to clean. However, when using their own resources, you may need to do some extra cleaning.

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

grammar

In the definition of the class, each class can have at most one destructor. Destructor without any parameters, without parentheses in the wording:

deinit {
    // 执行析构过程
}

Examples

var counter = 0;  // 引用计数器
class BaseClass {
    init() {
        counter++;
    }
    deinit {
        counter--;
    }
}

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

The above program execution output is:

1
0

When the show = nil statement is executed, the calculator minus 1, show the memory will be freed.

var counter = 0;  // 引用计数器

class BaseClass {
    init() {
        counter++;
    }
    
    deinit {
        counter--;
    }
}

var show: BaseClass? = BaseClass()

print(counter)
print(counter)

The above program execution output is:

1
1