1.什么是单例,及其优缺点是什么?
单例概念?单例就是一个类的单个实例。
单例的服务对象?整个应用。
单例通常用来做什么?当共享资源,实现窗口间传值。
优点:
1:一建全建,节省资源;
2:一改全改,方便修改;
3:单例接受的是受控访问;
缺点:
1:单例不能用来作为变化对象使用;
2:单例不能被继承,很难扩展;
3:单例的内存空间不能立即被释放,在应用程序终止后才会被释放;
单例在ARC中的实现
ARC中单例实现步骤
1 在类的内部提供一个static全局变量
2 提供一个类方法,让外界可以访问
3 重写+allocWithZone方法,为单例对象分配内存空间
4 重写-copyWithZone方法和-MutableCopyWithZone方法5 重写-MutableCopyWithZone方法
ARC中单例代码实现
#import "Tools.h"
@implementation Tools
// 创建静态对象 防止外部访问
static Tools *_instance;
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
// @synchronized (self) {
// // 为了防止多线程同时访问对象,造成多次分配内存空间,所以要加上线程锁
// if (_instance == nil) {
// _instance = [super allocWithZone:zone];
// }
// return _instance;
// }
// 也可以使用一次性代码
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
});
return _instance;
}
// 为了使实例易于外界访问 我们一般提供一个类方法
// 类方法命名规范 share类名|default类名|类名
+(instancetype)shareTools
{
//return _instance;
// 最好用self 用Tools他的子类调用时会出现错误
return [[self alloc]init];
}
// 为了严谨,也要重写copyWithZone 和 mutableCopyWithZone
-(id)copyWithZone:(NSZone *)zone
{
return _instance;
}
-(id)mutableCopyWithZone:(NSZone *)zone
{
return _instance;
}
单例在MRC中的实现
MRC单例实现步骤
1 在类的内部提供一个static修饰的全局变量
2 提供一个类方法,方便外界访问
3 重写+allocWithZone方法,保证永远都只为单例对象分配一次内存空间
4 严谨起见,重写-copyWithZone方法和-MutableCopyWithZone方法
5 重写release方法
6 重写retain方法
7 建议在retainCount方法中返回一个最大值
配置MRC环境
1 注意ARC不是垃圾回收机制,是编译器特性
2 配置MRC环境:build setting ->搜索automatic ref->修改为N0
MRC中单例代码实现
配置好MRC环境之后,在ARC代码基础上重写下面的三个方法即可
-(oneway void)release
{
}
-(instancetype)retain
{
return _instance;
}
-(NSUInteger)retainCount
{
return MAXFLOAT;
}
kvo和kvc的区别?
get和post的区别?
混合开发?
沙盒存储?