First of all we need to know how the apple to achieve a single case: 1. Can not call Alloc, a call on the collapse, in fact, is thrown exception (class inside the first call Alloc does not crash, the other crashes).
2. Provide a way for the outside world to obtain a singleton.
3. Create a single instance internally, when it is created, and create a singleton when the program starts.
Then we'll create a person class.
Person.h #import <Foundation/Foundation.h>@interface person:nsobject// get a single case + (instancetype) Shareperson; @end
person.m#import "Person.h"@implementation Person//Create object when program starts//Static VariablesStaticPerson *_instance =Nil;//role: Load class//What to call: Every time the program starts, it will load all the classes into memory+ (void) load{NSLog (@"%s", __func__); _instance=[[Self alloc] init]; }+(instancetype) shareperson{return_instance;}+(instancetype) alloc{if(_instance) {//The label has been allocated so that the outside world is not allowed to allocate memory//throw an exception and tell the outside world not to use distribution//' nsinternalinconsistencyexception ', Reason: ' There can only be one uiapplication instance. ' //Create Exception class//Name: Names of exceptions//Reson: The cause of the exception//UserInfo: Exception informationNSException *EXCP = [NSException exceptionwithname:@"nsinternalinconsistencyexception"Reason@"There can is only a person instance."Userinfo:nil]; //Throw Exception[EXCP raise]; } //super-and NSObject know how to allocate memory//Call the system default practice, when overriding a method, if you do not want to overwrite the original implementation, call Super return[Super alloc];}
Here I just want to simulate how the bottom of the Apple implementation of a singleton, we generally do not use this method. We will generally use the following methods:
+(instancetype) sharedperson{ // static variable statics person *_instance = Nil ; Static dispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{ = [[self alloc]init]; }); return _instance;}
iOS great God class Note 02-imitate Apple to create a singleton