iOS 再谈单例的几种写法

1.为什么再谈?

常规的单例写法有两种
+ (Student *)defaultInstance
{
static Student *defaultInstance = nil;
if (!defaultInstance)
{
defaultInstance = [[self alloc] init];
}
return defaultInstance;
}

+ (Student *)sharedManager
{
static Student *sharedInstance = nil;
static dispatch_once_t predicate;//此象必须是全局或者静态对象才能保证唯一性
dispatch_once(&predicate, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}

这两种写法的优缺点都是老生常谈,本文不再赘述。
这两种写法的最大问题其实是不能保证别人只通过这种方式获取该对象。若直接使用Student *std = [Student alloc] init];的方式去创建对象,则获取到的是一个新的对象。

2.解决方案

模仿UIApplication重写init方法。调用init时抛出异常,禁止别人调用。

  • 在.m文件中
    static Student *student = nil;

    + (void)load
    {
        student = [[self alloc] init];
    }
    
    //此方法和load选一个写即可,两个方法的区别下篇文章讲
    //+ (void)initialize
    //{
       // student = [[self alloc] init];
    //}
    
    + (instancetype)shareInstance
    {
        return student;
    }
    
    - (instancetype)init
    {
        if (student)
        {
            //抛异常
            NSException *exp = [NSException exceptionWithName:NSInternalInconsistencyException reason:@"There can only be one Student instance." userInfo:nil];
            [exp raise];
        }
        return [super init];
    }
    

如这样处理,在调用init时会抛出异常。

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'There can only be one Student instance.'
.
.//省略无关内容
.
libc++abi.dylib: terminating with uncaught exception of type NSException
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,838评论 0 9
  • 一个人的时光,是自己最安静的时刻。安静时的自己,可以幻想好多好多种的未来,可以把最美的梦装点在这个只属于自己的夜晚...
    夜落y阅读 502评论 0 0
  • 由于纪云溪白天还要上班,所以在开业之前她就考虑要招一个人。可是这太不容易,她开不起太高的薪水,年轻人就觉得不划算,...
    见手青阅读 253评论 0 0
  • 我时不时给周围的人讲,我其实很内向的。然后,不管我说话的语气正经不正经,周围人总是略带鄙夷和嘲讽的反问:你?能滔滔...
    壹言肆韵阅读 563评论 3 1