Common IOS design modes-singleton mode (IOS development)
Common IOS design modes include Singleton mode, delegate mode, observer mode, and MVC mode.
The Singleton mode is described here.
Singleton Mode
-Problem: only one instance is used in the application (only instances of a class are required)
-Principle: A static attribute is encapsulated and a method for creating a static instance is provided.
-Application: Singleton type
// Singleton. h @ interface Singleton: NSObject + (Singleton *) sharedManager; @ property (nonatomic, strong) NSString * stingletonData; @ end
# Import "Singleton. h "@ implementation Singleton @ synthesize SingletonData = _ singletonData; static Singleton * sharedManager = nil; + (Singleton *) sharedManager {static exactly once; static dispatch_once_t onceToken; dispatch_once (& once, ^ {shardManager = [[self alloc] init] ;}); return shardManager ;}@ end
Contains a static variable singletonData. The class method adopts the GCD Technology (based on the multi-thread access technology of C language ), it only executes a code block ({}) once throughout the application lifecycle ({}). Dispatch_once_t is The GCD struct. A pointer must be passed during use.
The dispatch_once function ensures that the function is only run once, and also means that the running is thread-synchronized.