程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> Objective-C單例模式

Objective-C單例模式

編輯:關於C語言

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.Bkjia.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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved