What is a singleton and why is a single case required?
The role of the singleton pattern is to solve the problem of "only one instance in the application".
When we need a class, but not too concerned about the "class" itself, such as iOS devices have a gravity class uiaccelerometer, in fact, for the user, only need some method of this class, such as real-time access to data, get the status of X, Y, Z axis. So this class requires only one instance, and more instances will only take up more memory space.
A single example in practical application
first, in the company project I was exposed to, one of the single cases used was to record all Nsuserdefaults Single-instance pcsetting of information. Nsuserdefaults itself is a singleton, a class of lightweight data persistence saved by iOS.
For the creation of a singleton, we need:
1. Create a class that inherits from the NSObject, and declare a class method in the. h
@interface pcsettings:nsobject+ (pcsettings*) sharedsettings;
2. Create a static variable in the. m file, implement the Sharedsettings method, and override the Init method
StaticPcsettings *g_sharedsettings =Nil;+ (Pcsettings *) sharedsettings{if(G_sharedsettings = =Nil) {g_sharedsettings=[[Pcsettings alloc] init]; } returng_sharedsettings;}- (ID) init{ Self=[Super Init]; if(Self! =Nil) {Nsuserdefaults*prefs =[Nsuserdefaults Standarduserdefaults]; Hub_userid=[[prefs Objectforkey:key_hubuserid] copy]; . . . } returnSelf ;}
This completes the creation of a singleton.
Another method of creating a singleton by GCD
+ (Pcsettings *) sharedsettings{ static dispatch_once_t once; Dispatch_once (&once, ^{ = [[self alloc]init]; } return g_sharedsettings;}
In the above code, the Dispatch_once function is provided by GCD, which is to execute only once in the entire application life cycle of the contents of the code block. Dispatch_once can record whether the block of code has been called.
Other singleton classes in the OBJECTIVE-C syntax
1.UIApplication
This class responds to events such as low memory, app startup, background run, and app termination through application delegate objects.
+ sharedapplication Create
2.NSUserDefaults
Lightweight data storage class
+ standarduserdefaults Create
3.NSNotificationCenter
Notification mechanism using the observer pattern
+ Defaultcenter Create
4.NSFileManager
Provides common operations for accessing file systems, locating, creating, copying Files and folders
+ Defaultmanager Create
5.NSBundle
Operation of local resources, access to file system and other functions
+ Mainbundle Create
Singleton mode in the iOS language