关于ios:如何在swift中创建Singleton对象

How to Create Singleton Object in swift

我正在以快速有效的方式学习创建单例类的单例模式,并找到了下面的最佳创建方法。

1
2
3
class SingletonClass{
    static let sharedInstance = SingletonClass()
}

因为我已经使用了let语句,所以它是只读属性,必须是线程安全的,所以在目标C中不需要调度一次()。我猜,static用于使sharedInstance变量成为class变量。

但是,如何保证整个应用程序中只创建一个实例呢?有什么小东西我不见了吗?


如果要防止类的实例化(有效地将用法限制为仅单例),则将初始值设定项标记为private

1
2
3
4
5
6
7
8
class SingletonClass {

    static let shared = SingletonClass()

    private init() {
        // initializer code here
    }
}


保证它只创建一次的是关键字static。您可以参考本文:https://thatthinginswift.com/singletons网站/

希望有帮助。

The static keyword denotes that a member variable, or method, can be
accessed without requiring an instantiation of the class to which it
belongs. In simple terms, it means that you can call a method, even if
you've never created the object to which it belongs


使私有初始化,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
final class Singleton {

    // Can't init is singleton
    private init() { }

    //MARK: Shared Instance

    static let sharedInstance: Singleton = Singleton()

    //MARK: Local Variable

    var emptyStringArray : [String] = []

}

你说得对。您可能希望读取文件和初始化,了解如何在swift中处理全局变量和静态变量。

迅速使用这种方法

Initialize lazily, run the initializer for a global the first time it
is referenced, similar to Java.

它说

it allows custom initializers, startup time in Swift scales cleanly
with no global initializers to slow it down, and the order of
execution is completely predictable.

The lazy initializer for a global variable (also for static members of
structs and enums) is run the first time that global is accessed, and
is launched as dispatch_once to make sure that the initialization is
atomic. This enables a cool way to use dispatch_once in your code:
just declare a global variable with an initializer and mark it
private.