ios什么是单例
单例模式是ios里面经常使用的模式,例如
[UIApplicationsharedApplication] (获取当前应用程序对象)、[UIDevicecurrentDevice](获取当前设备对象);
单例模式的写法也很多。
第一种:
- statiCSingleton*singleton=nil;
- https://非线程安全,也是最简单的实现
- +(Singleton*)sharedInstance
- {
- if(!singleton){
- https://这里调用alloc方法会进入下面的allocWithZone方法
- singleton=[[selfalloc]init];
- }
- returnsingleton;
- }
- https://这里重写allocWithZone主要防止[[Singletonalloc]init]这种方式调用多次会返回多个对象
- +(id)allocWithZone:(NSZone*)zone
- {
- if(!singleton){
- NSLog(@"进入allocWithZone方法了...");
- singleton=[superallocWithZone:zone];
- returnsingleton;
- }
- returnnil;
- }
第二种:
- https://加入线程安全,防止多线程情况下创建多个实例
- +(Singleton*)sharedInstance
- {
- @synchronized(self)
- {
- if(!singleton){
- https://这里调用alloc方法会进入下面的allocWithZone方法
- singleton=[[selfalloc]init];
- }
- }
- returnsingleton;
- }
- https://这里重写allocWithZone主要防止[[Singletonalloc]init]这种方式调用多次会返回多个对象
- +(id)allocWithZone:(NSZone*)zone
- {
- https://加入线程安全,防止多个线程创建多个实例
- @synchronized(self)
- {
- if(!singleton){
- NSLog(@"进入allocWithZone方法了...");
- singleton=[superallocWithZone:zone];
- returnsingleton;
- }
- }
- returnnil;
- }
第三种:
- __strongstaticSingleton*singleton=nil;
- https://这里使用的是ARC下的单例模式
- +(Singleton*)sharedInstance
- {
- https://diSPAtch_once不仅意味着代码仅会被运行一次,而且还是线程安全的
- staticdispatch_once_tpred=0;
- dispatch_once(&pred,^{
- singleton=[[superallocWithZone:NULL]init];
- });
- returnsingleton;
- }
- https://这里
- +(id)allocWithZone:(NSZone*)zone
- {
- /*这段代码无法使用,那么我们如何解决alloc方式呢?
- dispatch_once(&pred,^{
- singleton=[superallocWithZone:zone];
- returnsingleton;
- });
- */
- return[selfsharedInstance];
- }
- -(id)copyWithZone:(NSZone*)zone
- {
- returnself;
- }