ios-Single-Case mode
What is a singleton mode, that is, if in an application, if you want the instance of a class to use the same, you set the class to Singleton mode, there are many singleton pattern classes in the iOS infrastructure, such as Nsuserdefault, Nsnotificationcenter and so on are the design of the singleton pattern.
Design criteria for a singleton pattern:
1. Obtain a singleton instance through a class method,
2. Must be atomic to ensure multi-threaded access security
3. Define a static pointer variable that will persist throughout the lifetime of the application and, once initialized, will always point to the instance that was created for the first time.
Header file:
#import <Foundation/Foundation.h> @interface singleinstance:nsobject+ (singleinstance *) Sharedobject; @end
Implementation file:
#import "SingleInstance.h"//declares a static SingleInstance object pointer, which is static, so there will always be static singleinstance throughout the lifetime of the application *_ Shareobject = nil, @implementation singleinstance+ (singleinstance *) sharedobject{ @synchronized (self) { if (_ Shareobject = = nil)//Ensure that the static _shareobject pointer is initialized only once _shareobject = [[Self alloc] init]; } gcd mode// static dispatch_once_t oncetoken;// dispatch_once (&oncetoken, ^{// _shareobject = [[ Self alloc] init];// }); return _shareobject;} -(ID) init{self = [super init]; if (self) { //Singleton member variable initialization work } return self; @end
Use and results:
for (int i= 0; i<5; i++) { NSLog (@ "%d output singleinstance =%@", i,[singleinstance Sharedobject]); }
2015-04-02 20:22:30.692 single[644:15707] Section 0 Secondary Output singleinstance = <SingleInstance:0x7fa310d49a30>
2015-04-02 20:22:30.693 single [644:15707] First 1 output singleinstance = <SingleInstance:0x7fa310d49a30>
2015-04-02 20:22:30.693 single [644:15707] first 2 outputs SingleInstance = <SingleInstance:0x7fa310d49a30>
2015-04-02 20:22:30.693 single [644:15707] first 3 output singleinstance = <SingleInstance:0x7fa310d49a30>
2015-04-02 20:22:30.693 single [644:15707] first 4 outputs SingleInstance = <SingleInstance:0x7fa310d49a30>
ios-Single-Case mode