当前位置: 移动技术网 > 移动技术>移动开发>IOS > 面试必看 iOS单例模式

面试必看 iOS单例模式

2020年07月17日  | 移动技术网移动技术  | 我要评论

单例模式

• 单例模式的作用

可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问
从而方便地控制了实例个数,并节约系统资源

• 单例模式的使用场合

在整个应用程序中,共享一份资源(这份资源只需要创建初始化1次)

• ARC中,单例模式的实现

在.m中保留一个全局的static的实例
static id _instance;
重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

提供1个类方法让外界访问唯一的实例

+ (instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

实现copyWithZone:方法

- (id)copyWithZone:(struct _NSZone *)zone
{
    return _instance;
}

 

 

 

本文地址:https://blog.csdn.net/weixin_41963895/article/details/80146584

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网