A singleton is often used in iOS development, for example, each iOS program is itself a singleton, and a singleton is used, for example, to store personal preferences. So how do we write a singleton class on our own, with our own singleton object? Here is a single example of the code I wrote in the header file, this file is mainly some macros. The steps are written in detail, and arc or MRC can be used.
Singleton.h
Macro for a single case
/*
How to use
1: Include this header file
2: The name in the. h file that always contains Singleton_h (name) is the one you want to generate the singleton object in.
3: The name in the. m file that contains Singleton_m (name) is the one you want to generate the singleton object in.
Note that the name in step 2, 3 is consistent
4: Write init initialization method, because each singleton class initializes the content is different, so did not write to the macro inside, when creating a singleton class remember to write the Init method
5: Create singleton Object [class name Share+ (name)]
For example, we create a singleton for the person class: 1 Singleton_h (person) in person's. h file
2 Singleton_m (person) in the. m file of person
3 Write initialization method in the. m file of person
-(Instancetype) init{
static ID obj;
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
if ((obj = [super init])) {
The initialization of this class is done here
}
});
self = obj;
return self;
}
}
4 contains the head file of this class of person in the place of use [person Shareperson];
# #: Connection Strings and Parameters
\: Indicates the next line is also the contents of the current row
*/
#ifndef Singleton_h
#define Singleton_h
#define SINGLETON_H (name) + (instancetype) share# #name;
#if __has_feature (OBJC_ARC)//Arc
#define SINGLETON_M (name) \
Static ID instance;\
+ (Instancetype) Allocwithzone: (struct _nszone *) zone{\
\
Static dispatch_once_t oncetoken;\
Dispatch_once (&oncetoken, ^{\
instance = [Super Allocwithzone:zone];\
});\
\
Return instance;\
}\
\
+ (instancetype) share# #name {\
return [[Self alloc]init];\
}\
+ (ID) copywithzone: (struct _nszone *) zone{\
Return instance;\
}
#else//Non-arc
#define SINGLETON_M (name) \
Static ID instance;\
+ (Instancetype) Allocwithzone: (struct _nszone *) zone{\
\
Static dispatch_once_t oncetoken;\
Dispatch_once (&oncetoken, ^{\
instance = [Super Allocwithzone:zone];\
});\
\
Return instance;\
}\
\
+ (instancetype) share# #name {\
return [[Self alloc]init];\
}\
\
-(OneWay void) release{\
\
\
}\
-(Instancetype) autorelease{\
Return instance;\
}\
\
-(Instancetype) retain{\
Return instance;\
}\
\
+ (ID) copywithzone: (struct _nszone *) zone{\
Return instance;\
}\
\
-(Nsuinteger) retaincount{\
Return 1;\
}
#endif
#endif
A singleton in IOS development