读文网>知识>知识百科>百科知识

ios什么是单例

单例模式是ios里面经常使用的模式,例如

[UIApplicationsharedApplication] (获取当前应用程序对象)、[UIDevicecurrentDevice](获取当前设备对象);

单例模式的写法也很多。

第一种:

Java代码#FormatImgID_0#
  1. statiCSingleton*singleton=nil;
  2. https://非线程安全,也是最简单的实现
  3. +(Singleton*)sharedInstance
  4. {
  5. if(!singleton){
  6. https://这里调用alloc方法会进入下面的allocWithZone方法
  7. singleton=[[selfalloc]init];
  8. }
  9. returnsingleton;
  10. }
  11. https://这里重写allocWithZone主要防止[[Singletonalloc]init]这种方式调用多次会返回多个对象
  12. +(id)allocWithZone:(NSZone*)zone
  13. {
  14. if(!singleton){
  15. NSLog(@"进入allocWithZone方法了...");
  16. singleton=[superallocWithZone:zone];
  17. returnsingleton;
  18. }
  19. returnnil;
  20. }

第二种:

Java代码#FormatImgID_1#
  1. https://加入线程安全,防止多线程情况下创建多个实例
  2. +(Singleton*)sharedInstance
  3. {
  4. @synchronized(self)
  5. {
  6. if(!singleton){
  7. https://这里调用alloc方法会进入下面的allocWithZone方法
  8. singleton=[[selfalloc]init];
  9. }
  10. }
  11. returnsingleton;
  12. }
  13. https://这里重写allocWithZone主要防止[[Singletonalloc]init]这种方式调用多次会返回多个对象
  14. +(id)allocWithZone:(NSZone*)zone
  15. {
  16. https://加入线程安全,防止多个线程创建多个实例
  17. @synchronized(self)
  18. {
  19. if(!singleton){
  20. NSLog(@"进入allocWithZone方法了...");
  21. singleton=[superallocWithZone:zone];
  22. returnsingleton;
  23. }
  24. }
  25. returnnil;
  26. }


第三种:

Java代码#FormatImgID_2#
  1. __strongstaticSingleton*singleton=nil;
  2. https://这里使用的是ARC下的单例模式
  3. +(Singleton*)sharedInstance
  4. {
  5. https://diSPAtch_once不仅意味着代码仅会被运行一次,而且还是线程安全的
  6. staticdispatch_once_tpred=0;
  7. dispatch_once(&pred,^{
  8. singleton=[[superallocWithZone:NULL]init];
  9. });
  10. returnsingleton;
  11. }
  12. https://这里
  13. +(id)allocWithZone:(NSZone*)zone
  14. {
  15. /*这段代码无法使用,那么我们如何解决alloc方式呢?
  16. dispatch_once(&pred,^{
  17. singleton=[superallocWithZone:zone];
  18. returnsingleton;
  19. });
  20. */
  21. return[selfsharedInstance];
  22. }
  23. -(id)copyWithZone:(NSZone*)zone
  24. {
  25. returnself;
  26. }

相关热搜

相关文章

【百科知识】热点

【百科知识】最新