天天看点

使用GCD中dispatch_once创建单例

dispach_once函数中的代码块只会被执行一次,而且还是线程安全的。

+ (instancetype)SharedInstance {

//   普通方法

//    if (instance == nil) {

//        instance = [[super alloc] init];

//    }

//    普通多线程加锁方法

//    if (instance == nil) {//防止重复加锁

//    加锁 保证一次只能进来一个线程

//        @synchronized(self) {

//            if (instance == nil) {

//                instance = [[super allocWithZone:nil] init];

//            }

//        }

//    }

//    GCD设置只调用一次

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

//        instance = [[super alloc] init];//还是会有重复导入 这里alloc会默认调用self的allocWithZone

        instance = [[super allocWithZone:nil] init];

        NSLog(@"self = %@,super = %@",[self class],[super class]);//返回同一个类

    });

    return instance;

}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {

    NSLog(@"调用了自己的allocWithZone");

    return [self SharedInstance];

}

- (id)copy{

    return self;

}

其中第一个参数predicate,该参数是检查后面第二个参数所代表的代码块是否被调用的谓词,第二个参数则是在整个应用程序中只会被调用一次的代码块。

void _dispatch_once(dispatch_once_t *predicate, dispatch_block_t block)

{

if (DISPATCH_EXPECT(*predicate, ~0l) != ~0l) {

dispatch_once(predicate, block);

}

}

单例创建时最好不要给自己的属性赋值 可能导致相互引用

继续阅读