Objective-C單例模式

來源:互聯網
上載者:User

標籤:

單例類是一種特殊的類,在一個進程種只會存在一個該類的對象,在iOS應用中只會出現一個對象。這種設計模式在系統架構中許多地方都使用了,如NSFileManager、UIApplication等。

  • 在ARC的環境下,介面檔案為:
////  DVISingleton.h////  Copyright (c) 2014 長沙戴維營教育. All rights reserved.//#import <Foundation/Foundation.h>@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];}- (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

Objective-C單例模式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.