Xcode7.2编写单例模式

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

首先要控制类的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)类的对象,返回的都是同一个对象指针(地址).

运行效果图:

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

如有错误,请各位大神提出,小弟会第一时间改进。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值