设为首页 加入收藏

TOP

Objective-C单例模式
2015-03-19 03:34:59 来源: 作者: 【 】 浏览:188
Tags:Objective-C 单例 模式

单例类是一种特殊的类,在一个进程种只会存在一个该类的对象,在iOS应用中只会出现一个对象。这种设计模式在系统框架中许多地方都使用了,如NSFileManager、UIApplication等。

singleton

  • 在ARC的环境下,接口文件为:
    //
    //  DVISingleton.h
    //
    //  Copyright (c) 2014 长沙戴维营教育. All rights reserved.
    //
    
    #import 
         
           @interface DVISingleton : NSObject + (instancetype)sharedSingleton; @end 
         

    实现文件:

    //
    //  DVISingleton.m
    //
    //  Copyright (c) 2014 长沙戴维营教育. All rights reserved.
    //
    
    #import "DVISingleton.h"
    
    @implementation DVISingleton
    
    + (instancetype)sharedSingleton
    {
        static DVISingleton *sharedObject = nil;
    
        //线程安全,只允许执行依次
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            //使用父类的allocWithZone:方法创建对象
            sharedObject = [[super allocWithZone:NULL] init];
        });
    
        return sharedObject;
    }
    
    - (id)init
    {
        if (self = [super init]) {
    
        }
    
        return self;
    }
    
    + (id)allocWithZone:(struct _NSZone *)zone
    {
        return [self sharedSingleton];
    }www.2cto.com
    
    - (id)copy
    {
        return self;
    }
    
    - (void)dealloc
    {
    
    }
    @end
    
    • 在非ARC环境下的实现文件:
      #import "DVISingleton.h"
      
      @implementation DVISingleton
      
      + (instancetype)sharedSingleton
      {
          static DVISingleton *sharedObject = nil;
      
          //线程安全,只允许执行依次
          static dispatch_once_t onceToken;
          dispatch_once(&onceToken, ^{
              //使用父类的allocWithZone:方法创建对象
              sharedObject = [[super allocWithZone:NULL] init];
          });
      
          return sharedObject;
      }
      
      + (id)allocWithZone:(NSZone *)zone {
        return [[self sharedSingleton] retain];
      }
      - (id)copyWithZone:(NSZone *)zone {
        return self;
      }
      - (id)retain {
        return self;
      }
      - (unsigned)retainCount {
        return UINT_MAX; //denotes an object that cannot be released
      }
      - (oneway void)release {
        // never release
      }
      - (id)autorelease {
        return self;
      }
      - (id)init {
        if (self = [super init]) {
      
        }
        return self;
      }
      - (void)dealloc {
        [super dealloc];
      }
      @end
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C语言笔记之存储类 下一篇C编译器剖析_C语言的变参函数

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: