#import "ViewController.h"
#import "CZTool.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
});
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
for (int i = 0; i < 1000 * 1000; ++i) {
CZTool *tool = [CZTool shareTool];
}
NSLog(@"一次性执行的单例 : %f",CFAbsoluteTimeGetCurrent() - start);
start = CFAbsoluteTimeGetCurrent();
for (int i = 0; i < 1000 * 1000; ++i) {
CZTool *tool = [CZTool syncTool];
}
NSLog(@"互斥锁的单例 : %f",CFAbsoluteTimeGetCurrent() - start);
}
- (void)onceDemo {
NSLog(@"start");
static dispatch_once_t onceToken;
static NSObject *obj;
dispatch_once(&onceToken, ^{
NSLog(@"真的是一次吗?");
obj = [[NSObject alloc]init];
});
NSLog(@"%@",obj);
NSLog(@"end");
}
@end
#import <Foundation/Foundation.h>
@interface CZTool : NSObject
+ (instancetype)shareTool;
+ (instancetype)syncTool;
@end
#import "CZTool.h"
@implementation CZTool
+ (instancetype)shareTool {
static dispatch_once_t onceToken;
static id instance;
dispatch_once(&onceToken, ^{
instance = [[self alloc]init];
});
return instance;
}
+ (instancetype)syncTool {
static id instance;
@synchronized(self) {
if (instance == nil) {
instance = [[self alloc]init];
}
}
return instance;
}
@end
#import <Foundation/Foundation.h>
@interface CZTest : NSObject
@end
#import "CZTest.h"
@implementation CZTest
static dispatch_once_t onceToken;
static id instance;
+ (instancetype)shareTool {
dispatch_once(&onceToken, ^{
instance = [[self alloc]init];
});
return instance;
}
+ (void)reset {
onceToken = 0;
instance = nil;
}
@end