iOS 知识收集面试题

iOS-正确单例的写法

2019-03-07  本文已影响0人  枫叶无处漂泊

前言

单例应该是iOS中很简单的设计模式,写个单例很简单很方便。网上例子也很多,大家也是基本上copy下来就可以了,但是要知其所以然这个问题的文章就很少。所以我在这写一下好的单例,以及为什么这样么写。

创建单例的几种方式

一、单线程模式单例

    + (instancetype)sharedInsance{
        static Singleton *singleton = nil;
        if (!singleton ) {
            singleton = [[Singleton alloc] init];
        }
        return singleton;
    }

二、多线程加锁单例

+ (instancetype)sharedInsance {
    static Singleton *singleton;
    @synchronized (self) {
        if (!singleton) {
            singleton = [[Singleton alloc] init];
        }
    }
    return singleton;
}

三、多线程加锁单例

    + (instancetype)sharedLoadData {
        static Singleton *singleton = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            singleton = [[Singleton alloc] init];
        });
    return singleton;
    }

dispatch_once执行的流程

单例的健壮性

要是自己用的话,直接用shareInstance方法创建没啥问题,但是如果同组或者别人没注意用alloc创建、或者别人不小心使用copy、mutableCopy就可能产生两个实例,也就不存在单例。健壮性就是要保持怎么创建就这个实力,就返回位子的内存地址。

static Singleton* _instance = nil;
+ (instancetype)shareInstance {
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[super allocWithZone:NULL] init] ;
        //不是使用alloc方法,而是调用[[super allocWithZone:NULL] init] 
        //已经重载allocWithZone基本的对象分配方法,所以要借用父类(NSObject)的功能来帮助出处理底层内存分配的杂物
    }) ;
    return _instance ;
    }
 
 //用alloc返回也是唯一实例
+(id) allocWithZone:(struct _NSZone *)zone {
    return [Singleton shareInstance] ;
}
//对对象使用copy也是返回唯一实例
-(id)copyWithZone:(NSZone *)zone {
    return [Singleton shareInstance] ;//return _instance;
}
 //对对象使用mutablecopy也是返回唯一实例
-(id)mutableCopyWithZone:(NSZone *)zone {
    return [Singleton shareInstance] ;
}
@end    

上面代码注意点:

结尾

写一个健壮的单例,知其所以然,才能更好的理解的单例。大家加油!!

上一篇下一篇

猜你喜欢

热点阅读