This is my first opening of the park, as to why to write a singleton mode, because I am learning iOS at the beginning of the singleton mode of the concept of a vague, deliberately in this to do a collation, I hope to share with you.
One, the concept of iOS singleton mode (what is singleton mode)
The main point of the singleton pattern is that there is only one instance. What is an instance? Example is the object of a name, object instantiation, with the predecessor of a metaphor is said: The production of moon cakes is a kind of abrasive, moon cakes are objects, the process of making mooncakes is called object instantiation.
This class has only one instance, which we call a singleton class. This singleton class needs to provide its instance to the whole project or to the various classes in it, in layman's words, Xiao Ming (instance object) in the first grade four classes, he can be called to the language office, can also be named by the math office.
Merit, the instance only one, you say,,,,
Second, the application of single-case model
Here is one of my demo, very popular (singleton mode in general, how to create the use of)
DAO.h
1 #import <Foundation/Foundation.h>2@interface dao:nsobject3 + (DAO *) Shareddao; //class method
4-(void) printyourname; //instance method, which is what happens when an instance is done @end
Dao.m
1 #import "DAO.h"2 StaticDAO *instance=Nil; //Statically instantiate an object, why it is static, because the class method is also called a static method 3 @implementationDAO4 5+ (DAO *) Shareddao //Determines if the instance is empty, initializes it, and the function is to obtain a DAO singleton object 6 {7 if(instance==Nil)8 {9Instance=[[DAO alloc] init];Ten } One returninstance; A }
-
-(void) printyourname//instance method, which will be called in BL.M
15 {
NSLog (@ "Zhang San");
17}
@end
BL.h
1 #import <Foundation/Foundation.h>2#import"DAO.h" 3 4 @interface Bl:nsobject 5 6 @property (nonatomic,strong) DAO *DAO; //Create an object called DAO 7 8 @end
bl.m
1 #import "BL.h"2 3 4 5 @implementationBL6- (ID) init //initialization 7 {8self=[Super init];9 if(self)Ten { Oneself.dao=[DAO Shareddao]; //obtained a singleton object A - [Self.dao Printyourname]; //Use this Singleton object to invoke the instance method in DAO.M - the } - returnSelf ; - } - + @end
This is a relatively simple demo, hand hit part, may have flaws to correct.
For students who have just learned iOS, they may be helpful. In the MVC development model is often used to, of course, this demo is relatively elementary, can save memory space and time, but there is a multi-threaded state of concurrency problems, of course, there are many improvements on the Internet, we can search for learning.
iOS Development: Single-instance mode