1. What is a singleton mode?
The popular saying is: A class, can only instantiate once
2. Under what circumstances is a singleton mode used?
① creates instances with wasted resources, and the more instances are not controlled.
② when different threads are called, they may cause a different behavior.
③ instances to be accessed between multiple modules
④ other ...
3. Simple implementation
Here is an example of a student class to illustrate
@interface Student:nsobject + (instancetype) sharedstudent; @end #import " student.h " static Student* __stu; @implementation Student + (instancetype) sharedstudent{ if (__ Stu == nil) {__stu = [[Student Alloc]init]; return __stu;} @end
The above example is one of the simplest implementations of a single example (just to illustrate what a singleton is)
Here is a lazy approach, but also a common method of practical work, using macros to define the declaration and definition of a single case
#defineSynthesize_singleton_for_header (className) \+ (ClassName *) shared# #className;#defineSynthesize_singleton_for_class (className) \+ (ClassName *) shared# #className {StaticClassName *shared# #className =Nil;Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{shared# #className=[[Self alloc] init];}); returnshared# #className;}//using Dispatch_once, this method means that this method executes only once during the application life cycle, which is a single-instance code that combines GCD under arc.
When used, you only need to write the corresponding code in the header file with the implementation file.
Also take student example, here I put this macro definition in a single header file Singleton.h
#import <Foundation/Foundation.h>#import"Singleton.h"@ Interface Student:nsobjectsynthesize_singleton_for_header (Student); @end #import " Student.h " @implementation Studentsynthesize_singleton_for_class (Student); @end
IOS Learning Note--0008 (singleton mode)