您的位置:首页 > 移动开发

Xcode7.2编写单例模式

2015-12-25 20:43 393 查看
单例模式最根本的问题就是要保证一个类只能生成一个对象(实例),不管类生成多少个对象,始终都返回一个对象给用户。

首先要控制类的alloc方法,我们就必须重写以下方法:

<span style="font-size:32px;">+(instancetype)allocWithZone:(struct _NSZone *)zone</span>

详细代码如下:

<span style="font-size:32px;">+(instancetype)allocWithZone:(struct _NSZone *)zone
{
@synchronized(self) {
if (singlton == nil) {
@synchronized(singlton) {
singlton = [super allocWithZone:zone];
}
}
}
return singlton;
}</span>
重写完成后,给类提供一个单例方法:

<span style="font-size:32px;">+(instancetype)shareSingletons
{
return [[self alloc] init];
}</span>
最后就是在使用单例对象的时候,导入头文件即可。

方法如下:

<span style="font-size:32px;">//  Copyright © 2015年 bao. All rights reserved.
//

#import "ViewController.h"
#import "Singletons.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
Singletons * s1 = [Singletons shareSingletons];
Singletons * s2 = [Singletons shareSingletons];
Singletons * s3 = [Singletons shareSingletons];
NSLog(@"1=%p  2=%p   3=%p", s1, s2, s3);
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end</span><span style="font-size:32px;">
</span>
不管创建了多少个单例(Singletons)类的对象,返回的都是同一个对象指针(地址).

运行效果图:



可见打印的地址都是一样的,也就表明我们创建的对象不管多少个始终都是同一个,这就是单例对象。

如有错误,请各位大神提出,小弟会第一时间改进。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  苹果开发 app ios ui xcode