Apple Developer Documentation Archive(Singleton Part)を学ぶ

4401 ワード

Singleton


A singleton class returns the same instance no matter how many times an application requests it. A typical class permits callers to create as many instances of the class as they want, whereas with a singleton class, there can be only one instance of the class per process. A singleton object provides a global point of access to the resources of its class. Singletons are used in situations where this single point of control is desirable, such as with classes that offer some general service or resource.

You obtain the global instance from a singleton class through a factory method. The class lazily creates its sole instance the first time it is requested and thereafter ensures that no other instance can be created. A singleton class also prevents callers from copying, retaining, or releasing the instance. You may create your own singleton classes if you find the need for them. For example, if you have a class that provides sounds to other objects in an application, you might make it a singleton.
Several Cocoa framework classes are singletons. They include NSFileManager, NSWorkspace, and, in UIKit, UIApplication and UIAccelerometer. The name of the factory method returning the singleton instance has, by convention, the form sharedClassType. Examples from the Cocoa frameworks are sharedFileManager, sharedColorPanel, and sharedWorkspace. △もう一度見てください.これは授業の内容です.
ソース:https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/Singleton.html

Managing a Shared Resource Using a Singleton


Provide access to a shared resource using a single, shared class instance.

Overview


You use singletons to provide a globally accessible, shared instance of a class. You can create your own singletons as a way to provide a unified access point to a resource or service that’s shared across an app, like an audio channel to play sound effects or a network manager to make HTTP requests.

Create a Singleton


You create simple singletons using a static type property, which is guaranteed to be lazily initialized only once, even when accessed across multiple threads simultaneously:
class Singleton {
    static let sharedInstance = Singleton()
} //singleton 개념의 핵심
If you need to perform additional setup beyond initialization, you can assign the result of the invocation of a closure to the global constant:
class Singleton {
    static let sharedInstance: Singleton = {
        let instance = Singleton()
        // setup code
        return instance
    }()
}
ソース:https://www.notion.so/yagomacademy/86799a4a48bb4cb18645b4c087e45fb1?v=5a534b61f38c4130b27e1d9310f6613e&p=858183c9bfcf4897aca9b2b3f3b985fc