1, the introduction of a single case
Singleton is one of the most common development patterns for iOS.
2, what is a single case
A singleton is a class that creates only one object and allocates only one memory space.
3, single case of the application scenario
1) System of single example: [uiapplication sharedapplication];
2) Application of the single example: QQ background map, etc.
4. Precautions for single case
1) always allocate only one piece of memory to create objects
2) provides a class method that returns an internally unique object (one instance)
3) It is best to ensure that the Init method is initialized only once
5, the creation of a single case
1) Overriding the allocation memory method
// override method for allocating memory + (Instancetype) Allocwithzone: (struct _nszone *) zone{ static dispatch_once_t Once_token; Dispatch_once (&once_token, ^{ // guaranteed to allocate only once memory _instance = [ Super Allocwithzone:zone]; }); return _instance; }
2) Creating a class method
// Create share Method + (instancetype) shareperson{ static dispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{ // is only init once _instance = [[Self Alloc]init]; }); return _instance;}
3) Overriding the Init method
- (instancetype) init{ if (self = [Super init]) { static dispatch_once _t Oncetoken; Dispatch_once (&oncetoken, ^{ // Assignment, initialize resource }); return Self ;}
6. Single-instance invocation and output results
1) Invocation of a single case
Person * Mark = [person Shareperson]; person * Mary = [[Person alloc]init]; NSLog (@ "Mark---%p mary---- %p", mark,mary);
2) output of single case
2016-03-02 21:38:30.743 single[2104:190961] Mark---0x7fe6325488e0 mary----
After reading MJ's explanation of the single case of personal summary