//
// SingleObj.m
// Block
//
// Created by hongbaodai on 2018/11/26.
// Copyright © 2018年 Z. All rights reserved.
//
#import “SingleObj.h”
@implementation SingleObj
//1、++++++++++++++++++++++線程不安全,如果在一個runloop中是安全l的
//+(instancetype)shareInstance {
// static SingleObj *obj = nil;
// if (!obj) {
// obj = [[SingleObj alloc] init];
// }
// return obj;
//}
//2、++++++++++++++++++++++上面的改進 加鎖,但影響性能
//+(instancetype)shareInstance {
// static SingleObjt *obj = nil;
// @synchronized (self) {
// if (!obj) {
// obj = [[SingleObj alloc] init];
// }
// }
// return obj;
//}
//以上兩種如果不通過[SingleObj shareInstance] 而是[[SingleObj alloc] init]還會創建空間
//3、++++++++++++++++++++++ 不會創建空間,最優→_→
//+(instancetype)shareInstance {
// static SingleObj *obj = nil;
// static dispatch_once_t onceToken;
// dispatch_once(&onceToken, ^{
// obj = [[super allocWithZone:NULL] init];
// });
// return obj;
//}
//
//+ (instancetype)allocWithZone:(struct _NSZone *)zone {
// return [self shareInstance];
//}
//
//- (id)copyWithZone:(struct _NSZone *)zone {
// return self;
//}
//- (id)mutableCopyWithZone:(struct _NSZone *)zone {
// return self;
//}
//改進=======================================
static SingleObj *obj = nil;
+(instancetype)shareInstance {
if (!obj) {
obj = [[SingleObj alloc] init];
}
return obj;
}
- (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
obj = [super allocWithZone:zone];
});
return obj;
}
- (id)copyWithZone:(struct _NSZone *)zone {
return self;
} - (id)mutableCopyWithZone:(struct _NSZone *)zone {
return self;
}
@end