单例模式的作用
可以保证在程序运行过程,一个类只有一个实例,
而且该实例易于供外界访问,从而方便地控制了实例个数,并节约系统资源
单例模式的使用场合
在整个应用程序中,共享一份资源(这份资源只需要创建初始化1次)
单例模式在ARC\MRC环境下的写法有所不同,需要编写2套不同的代码
可以用宏判断是否为ARC环境
#if __has_feature(objc_arc)
// ARC
#else
// MRC
#endif
单例模式 - ARC
ARC中,单例模式的实现
在.m中保留一个全局的static的实例
static id _instance;
重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)
+ (id)allocWithZone:(struct _NSZone *)zone
{
@synchronized(self) {
if (!_instance) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}
提供1个类方法让外界访问唯一的实例
+ (instancetype)sharedSoundTool
{
@synchronized(self) {
if (!_instance) {
_instance = [[self alloc] init];
}
}
return _instance;
}
实现copyWithZone:方法
- (id)copyWithZone:(struct _NSZone *)zone
{
return _instance;
}
单例模式 – 非ARC
非ARC中(MRC),单例模式的实现(比ARC多了几个步骤)
实现内存管理方法
- (id)retain { return self; }
- (NSUInteger)retainCount { return 1; }
- (oneway void)release {}
- (id)autorelease { return self; }
系统中的单例模式:
UIDevice
类提供了一个单例对象,它代表着设备,通过它可以获得一些设备相关的信息,比如电池电量值(batteryLevel)、电池状态(batteryState)、设备的类型(model,比如iPod、iPhone等)、设备的系统(systemVersion)
通过[UIDevice currentDevice]可以获取这个单例对象
NSUserDefaults
[NSUserDefaults standardUserDefaults]
网友评论