MasterofProject

IOS development - implementation, use and architecture of one case

Label IOSSingle casedesign pattern
957 people read comments(2) Collection Report
Classification:

One case in our development is the most commonly used design patterns in the iOS is also the case. A single case can ensure that any instance of a class is only in the program, to facilitate the sharing of resources and data. The use of design principles is a single responsibility principle. We take a look at the iOS itself comes with the class or method which uses a single example of the model:

(1) UIAccelerometer and sharedAccelerometer method generally if a method name in have shared such words, we can think this is a can be shared by the entire application instance variables, is the use of single case.

(2) UIApplication and sharedApplication method, we use this method to create general global variables.

(3) class NSBundle and mainBundle methods.

(4) class NSFileManager and defaultManager methods.

(5) class NSNotificationCenter and defaultManager methods. Which NSNotificationCenter also implements the observer pattern.

(6) class NSUserDefaults and defaultUser methods.

Sample code uploaded to:Https://github.com/chenyufeng1991/iOS-Singleton.


[single case implementation]

(1) create a normal class, assuming the name for the statement of the Singleton. in Singleton.h a method, when the time comes using the method (Note: must be class methods, and is not an instance method) can create the only one instance of:

<Foundation/Foundation.h> #import

Singleton @class;

Singleton @interface: NSObject
/ / "+" class method, by calling
+ (Singleton *) sharedInstance;

@end

(2) in Singleton.m, you need to implement the sharedInstance method and your other business logic:

Singleton.h "#import"

Static / / declare a static instance of the class;
Singleton *_sharedInstance static = nil;

Singleton @implementation

/ * *
* 1 use the class method to generate the only instance of this class;
* /
+ (Singleton *) sharedInstance{
If (! _sharedInstance) {
=[[self alloc]init] _sharedInstance;
}
_sharedInstance return;
}

@end

Note: be sure to declare a static static variable. After the creation of the only instance of the class using the sharedInstance method, instead of using alloc, init.


(3) we use a simple demo to demonstrate a single case:

RootVC.h "#import"
Singleton.h "#import"

RootVC @interface ()

@end

RootVC @implementation

- (void) viewDidLoad
{
ViewDidLoad] [super;

TestSigleTon] [self;
}

- (void) testSigleTon
{
The result is that / / single case, call the class method simply returns a shared object
/ * *
* single and single2 are the same object;
Because the returned data is a static variable, the global unique;
* /
*single [Singleton = sharedInstance] Singleton;
*single2 [Singleton = sharedInstance] Singleton;

If (single = = single2) {
NSLog (@ "single = single2");
}

NSLog (@ single address:% @ ", single);
NSLog (@ single2 address:% @ ", single2);


}

@end

(4) the output is as follows:

.


Can be seen, the memory address of the two objects is the same that the two objects are actually the same object, singleton is achieved. This is single cases of the most widespread and the most simple way to achieve, in the project will be frequently used in does not involve multithreading is completely correct. However, we think more about, in the development of multi thread, the way to achieve this kind of security? Then how to achieve.


[single case structure]

In project development, if we like the same, in each class are using such write a method to generate single cases, will not seem very troublesome, it is redundant. Such repeated in each class repeat write code is not conducive to the development and structure, then we should use what method to extract code? The solution is to use a class (Category). For a brief introduction to the Category category, please refer toObjective-C - type (Category).". Specific implementation is as follows:

(1) to create a new Category, as an extension of the NSObject class. Because the nsobject class is the base class for most of the IOS, if use category as nsobject additional methods (shareInstance method), then all inherited from the nsobject class are can using the method. We commonly used UIViewController and UIView are inherited from the NSObject, so it will be very convenient.

.


(2) the following documents are generated by category Category:
.


Need a foreign exposure method to generate examples in the NSObject+Singleton.h header files, for other types of calls.

<Foundation/Foundation.h> #import

NSObject @interface (Singleton)

/ / "+" class method, by calling
+ (instancetype) sharedInstance;

@end


(3) in the NSObject+Singleton.m to realize the method, to generate a unique instance of a class. Here I use dictionary to store a certain class and the class of examples, is the form of key value pairs: the key is the name of the class, the value is an object. According to the name of the class to retrieve the whether the object has been created, if you can retrieve the name of the class, said has been created, it just returns the object; if there is no search to the class name, you need to create, created is also stored in the dictionary;

NSObject+Singleton.h "#import"

NSObject @implementation (Singleton)

A single instance of each storage / / the use of variable dictionary class, key class name, value is the object of the class;
/ / declared as static variables, you can save the last value;
NSMutableDictionary *instanceDict static;
Instance id;

+ (instancetype) sharedInstance {
@synchronized (self)
{
/ / initialize the dictionary;
If (instanceDict = = Nil) {
InstanceDict = alloc] init] [[NSMutableDictionary;
}

/ / get the class name;
*className NSString = NSStringFromClass (class] [self);
If (className) {
The object / / find a dictionary, use the class name to search, can ensure a class to be stored once;
Instance = instanceDict[className];
If (instance = = Nil) {
/ / object of the class is not instantiated on initialization, and according to the key value pairs are stored;
Instance = alloc] init] [[self.class;
SetValue:instance forKey:className] [instanceDict;
}else{
The object / / already stored in the dictionary, can be returned directly to instance;
}
}else{
Don't get / / class name, so make sure that sharedInstance is a kind of method, called class;
}

Instance return;
}
}
@end

(4) a single case of category has been finished, the following will be tested. Here I test methods are as follows: two interface between jump and return, use the same code generating class object; at the same time the new a person class and StudentModel class to test, two classes are inherited from the nsobject. There is no any implementation, only used to create objects. Don't forget to import the header file NSObject+Singleton.h "#import".

The first interface ViewController.m implementation is as follows:

ViewController.h "#import"
NSObject+Singleton.h "#import"
Person.h "#import"
StudentModel.h "#import"

ViewController @interface ()

@end

ViewController @implementation

- (void) viewDidLoad {
ViewDidLoad] [super;

}

- (void) viewDidAppear: (BOOL) animated{

ViewDidAppear:true] [super;

/ / use sharedInstance to create a class object;
*vc1 [ViewController = sharedInstance] ViewController;
*vc2 [ViewController = sharedInstance] ViewController;
NSLog (@ ViewController---vc1 address:% @ ", Vc1);
NSLog (@ ViewController---vc2 address:% @ ", vc2);

If (Vc1 = = vc2) {
NSLog (@ "ViewController---vc1 = vc2");
}

/ / create a loop of 5 Person objects, 5 objects are the same;
For (I int = 0; I < 5; i++) {
*per1 [Person = sharedInstance] Person;
NSLog (@ ViewController---per1 address:% @ ", Per1);
}

The use of alloc / / create objects, each object is different;
For (I int = 0; I < 5; i++) {
更新*柱= [ [更新] init函数];
nslog(@“视图---柱地址:% @“,梭哈);
}


}

“结束”


第二个界面secondviewcontroller M实现如下:

#进口”secondviewcontroller。”
#进口“NSObject +单。”
#进口”的人。”
#进口“更新。”
#进口”视图。”

“界面secondviewcontroller()

“结束”

“实施secondviewcontroller

* * * *
*在另一个界面中做同样的测试;
*
-(void)viewDidLoad {
[超级viewDidLoad ];

}

-(void)viewdidappear:(bool)动画{

[超级viewdidappear:动画];

secondviewcontroller * secondvc1 = [ secondviewcontroller sharedinstance ];
secondviewcontroller * secondvc2 = [ secondviewcontroller sharedinstance ];

nslog(@”secondviewcontroller --- secondvc1地址:% @“,secondvc1);
nslog(@”secondviewcontroller --- secondvc2地址:% @“,secondvc2);

如果(secondvc1 = = secondvc2){
nslog(@”secondviewcontroller --- secondvc1 = = secondvc2”);
}

为(int i = 0;i < 5;i++){
个人sharedinstance Per1 = [人];
nslog(@”secondviewcontroller ---每地址:% @“,PER1);
}

为(int i = 0;i < 5;i++){
更新*柱= [ [更新] init函数];
nslog(@”secondviewcontroller ---柱地址:% @“,梭哈);
}

}

* * * *
*返回上一界面,再次生成对象查看;
*
* @param发件人发件人描述# > < #
*
-(ibaction):(ID)发送{

【自dismissviewcontrolleranimated:真正的完成:零];
}

“结束”


下面分别是三个步骤打印日志:启动第一个界面、跳转到第二个界面、返回第一个界面。

启动第一个界面的输出:



跳转到第二个界面的输出:



再次返回到第一个界面的输出:



总结,通过以上打印输出,使用sharedinstance创建单例后,无论在哪一个界面,每个类的对象是唯一的。而使用alloc创建的对象往往都是不同的。通过以上的设计,就不需要在每一个类中都去实现sharedinstance方法了。



GitHub主页:https://github.com/chenyufeng1991欢迎大家访问!

最近极客学院维基正在进行它职业技能图谱的制定,我主要负责iOS方向,大家感兴趣的可以一起参加,有问题或者修改可以直接给我发问题或者拉请求。https://github.com/chenyufeng1991/skillmap


猜你在找
查看评论
*以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:167873次
    • 积分:六千八百九十四
    • 等级:
    • 排名:1709名第
    • 原创:466篇
    • 转载:36篇
    • 译文:0篇
    • 评论:212条
    联系方式
    开源项目
    博客专栏
    文章分类
    文章存档
    Latest comments