Singleton in iOS development, iOS development
In iOS development, Singleton is often used. For example, each iOS program is a Singleton, and a singleton is used for storage of personal preferences. So how can we write a singleton class by ourselves and use our singleton object? Below is the code in the header file of a single example I wrote. This file is mainly a number of macros. The steps are detailed and can be used by ARC or MRC. With this header file, as long as the file is included in use, it is basically OK. The following describes how to use it.
// Singleton. h
// Macro of the singleton
/*
Usage
1: Include this header file
2: The name in the. h file that contains singleton_h (name) is the name when you want to generate the singleton_h (name) object.
3: In the. m file, the name in singleton_m (name) is the name when you want to generate a singleton object.
Note that the names in steps 2 and 3 must be consistent.
4: Write the init initialization method. Because the initialization content of each Singleton class is different, it is not written to the macro. Remember to write the init method when creating the singleton class.
5: Create a singleton object [class name share + (name)]
For example, we create a Person class singleton_h (Person) in the. h file of Person)
2. singleton_m (Person) in the. m file of Person)
3. Write the 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]) {
// Initialize the class here
}
});
Self = obj;
Return self;
}
}
4. the header file of the Person class [Person sharePerson] is included in the usage.
// ###: Connection string and Parameters
// \: Indicates that the next row is also the content 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