iOS 单例设计模式 单例写法
来源:互联网 发布:倚天行情软件下载 编辑:程序博客网 时间:2024/06/12 03:41
//
// SingleTool.m
// ggggg
//
// Created by 草帽~小子 on 2017/9/13.
// Copyright © 2017年 HLJ. All rights reserved.
//
#import "SingleTool.h"
//提供一个static修饰的全局变量,强引用已经实例化的对象
static SingleTool *singleTool;
@implementation SingleTool
//实例化一个类方法,返回一个单例对象
+ (instancetype)shareTools {
//注意:这里建议使用self,而不是直接使用类名(考虑继承)
staticdispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
singleTool = [[selfalloc] init];
});
returnsingleTool;
}
//避免alloc产生新对象,所以需要重写allocWithZone方法
+ (instancetype)allocWithZone:(struct_NSZone *)zone {
/*
1、使用GCD
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
singTool = [super allocWithZone:zone];
});
*/
//1.使用GCD
staticdispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (singleTool ==nil) {
singleTool = [superallocWithZone:zone];
}
});
// //2.使用枷锁的方式、保证只分配一次存储空间
// @synchronized (self) {
//
// if (singleTool == nil) {
// singleTool = [super allocWithZone:zone];
// }
//
// }
//
returnsingleTool;
}
//copy返回一个不可变对象
- (id)copyWithZone:(NSZone *)zone {
//若原对象是不可变对象,那么返回原对象,并将其引用计数加1;
//return [[self class] allocWithZone:zone];
//若原对象是可变对象,那么创建一个新的不可变对象,并初始化为原对象的值,新对象的引用计数为 1。
returnsingleTool;
}
//mutableCopy 创建一个新的可变对象,并初始化为原对象的值,新对象的引用计数为 1;
-(id)mutableCopyWithZone:(NSZone *)zone{
returnsingleTool;
}
- iOS 单例设计模式 单例写法
- ios 单例模式的写法
- ios 单例模式 两种写法
- ios 单例模式的写法
- IOS 单例模式的写法
- iOS之单例模式常见写法
- iOS单例模式的官方写法
- iOS 单例模式的写法
- iOS 单例模式的写法
- iOS方法--------单例模式的写法
- 单例模式写法
- 单例模式写法
- 单例模式写法
- 单例模式写法
- iOS 单例写法
- ios 单例写法
- ios单例写法
- iOS单例写法
- The study of Higher-order function in Python(20170913)
- c++ 插入迭代器
- 数据结构和算法--二叉树的实现
- 总结 2017.9.13
- Java连接MnogoDb数据库
- iOS 单例设计模式 单例写法
- 绝对大佬的模板%%%
- iOS SDK的设计与实现
- js arguments关键字和callee
- Autodesk.PowerMill.2017.SP4
- MySql从一窍不通到入门(三)连接查询、联合查询、子查询
- Linux服务器上oracle数据库的导出expdp和导入impdb
- overview_java(四)-抽象
- jdbc连接sqlserver数据库