iOS單例初步理解

iOS單例初步理解

在iOS開發中,系統自帶的框架中使用了很多單例,非常方便用戶(開發者,使用比如[NSApplication sharedApplication] 等),在實際的開發中,有時候也需要設計單例對象,為保證每次獲取的對象都為同一個對象。
在iOS開發中創建單例具體步驟:
1.提供一個類方法:+ (instancetype)sharedXXXX;
2.創建一個全局靜態變量static id _instance;
3.重寫allocWithZone
4.重寫copyWithZone

特舉例子如下:
@interface MusicTool : NSObject
+ (instancetype)sharedMusicTool;
@end
static id _instance; // 全局變量
/**
* alloc方法內部會調用allocWithZone
*/
+ (id)allocWithZone:(struct _NSZone *)zone {
if (_instance == nil) {
@synchronized(self) {
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
}
return _instance;
}
/**
* 重寫copy方法,防止copy出錯
*/
- (instancetype)copyWithZone:(NSZone *)zone {
return _instance;
}

  • (instancetype)sharedMusicTool {
    if (_instance == nil) {
    @synchronized(self) {
    if (_instance == nil) {
    _instance = [[self alloc] init];
    }
    }
    }
    return _instance;
    }

第二種使用GCD創建單例方法
@interface DataTool : NSObject
+ (instancetype)shareDataTool;
@end
static id _instance;
+ (id)allocWithZone:(struct _NSZone *)zone {
if (_instance == nil) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
}
return _instance;
}
- (instancetype)copyWithZone:(NSZone *)zone {
return _instance;
}

  • (instancetype)shareDataTool {
    if (_instance == nil) {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
    _instance = [[self alloc]init];
    });
    }
    return _instance;
    }
    第三種使用餓漢模式
    @interface SoundTool : NSObject
  • (instancetype)sharedSoundTool;
    @end

static id _instance;
+ (void)load {
_instance = [[self alloc]init];
}

  • (instancetype)allocWithZone:(struct _NSZone *)zone {
    if (_instance == nil) {
    _instance = [super allocWithZone:zone];
    }
    return _instance;
    }

  • (instancetype)sharedSoundTool {
    return _instance;
    }

  • (instancetype)copyWithZone:(NSZone *)zone {
    return _instance;
    }

為保證兼容MRC還需要重寫
static id _instace;

  • (id)allocWithZone:(struct _NSZone *)zone
    {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
    _instace = [super allocWithZone:zone];
    });
    return _instace;
    }

  • (instancetype)sharedDataTool
    {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
    _instace = [[self alloc] init];
    });
    return _instace;
    }

  • (id)copyWithZone:(NSZone *)zone
    {
    return _instace;
    }

  • (oneway void)release { } //重寫release

  • (id)retain { return self; } //重寫retain
  • (NSUInteger)retainCount { return 1;} //重寫retainCount
  • (id)autorelease { return self;} //重寫autorelease

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/247147.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/247147.shtml
英文地址,請注明出處:http://en.pswp.cn/news/247147.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python面向對象之類的成員

面向對象之類的成員 細分類的組成成員 類大致分為兩塊區域: 第一部分:靜態字段 第二部分:動態方法 class Animal:type_name "動物類" # 靜態變量(靜態字段)__feature "活的" # 私有靜態變量…

python元類、反射及雙線方法

元類、反射及雙線方法 元類 print(type(abc)) print(type(True)) print(type(100)) print(type([1, 2, 3])) print(type({name: 太白金星})) print(type((1,2,3))) print(type(object))class A:passprint(isinstance(object,type)) print(isinstance(A, type)) type元類是獲取該…

iOS中的多線程一般使用場景

在IOS開發中為提高程序的運行效率會將比較耗時的操作放在子線程中執行,iOS系統進程默認啟動一個主線程,用來響應用戶的手勢操作以及UI刷新,因此主線程又叫做UI線程。 前面的Blog說明了NSThread以及GCD處理并發線程以及線程安全(線…

iOS中如何優化Cell中圖片的下載性能

在iOS開發中使用最為常見的是UITableView,其中UITabelViewCell中下載圖片,會影響用戶下拉刷新UI,導致卡頓,用戶體驗不好,在這篇blog中,我將以一個例子來說明如何優化UITableView下載圖片 1.使用懶加載方式&#xff0c…

【Yoshua Bengio 親自解答】機器學習 81 個問題及答案(最全收錄)

本文轉自:http://mp.weixin.qq.com/s?__bizMzI3MTA0MTk1MA&mid401958262&idx1&sn707f228cf5779a31f0933af903516ba6&scene1&srcid0121zzdeFPtgoRoEviZ3LZDG#rd 譯者:張巨巖 王婉婷 李宏菲 戴秋池 這是 Quora 的最新節目&#xf…

Java生鮮電商平臺-SpringCloud微服務架構中網絡請求性能優化與源碼解析

Java生鮮電商平臺-SpringCloud微服務架構中網絡請求性能優化與源碼解析 說明:Java生鮮電商平臺中,由于服務進行了拆分,很多的業務服務導致了請求的網絡延遲與性能消耗,對應的這些問題,我們應該如何進行網絡請求的優化與…

XCode7 創建framework

1.新建一個靜態庫工程. file→ new→ project, 彈出框中選擇iOS→ framework & library中的cocoa touch static library.點擊Next,輸入product name: TestFramework, 點擊Next→ 點擊Create. 2.刪除向導所生成工程中的Target. 點擊工程名→ 點擊TARGETS → 右鍵Delete. …

基礎js逆向練習-登錄密碼破解(js逆向)

練習平臺:逆向賬號密碼 https://login1.scrape.center/ 直接打開平臺,輸入密碼賬號,抓包找到加密的參數攜帶的位置,這邊我們找到的是一個叫token的加密參數,這個參數的攜帶是一個密文 我們首先考慮一下搜索這個加密的…

python之socket

socket套接字 什么叫socket socket是處于應用層與傳輸層之間的抽象層,他是一組操作起來非常簡單的接口(接受數據)此接口接受數據之后,交由操作系統.socket在python中就是一個模塊. socket兩個分類 基于文件類型的套接字家族 套接字家族的名字:AF_UNIX unix一切皆文件…

iOS----JSON解析

在iOS開發中與服務器進行數據交互操作,操作過程中使用最為常見的格式為JSON與XML,其中JSON較為清量,因此本篇blog就講解一下如何在iOS中進行JSON解析。 1.建立HTTP請求 (1)創建URL NSString *URLStr [NSString stringWithFormat:”http:/…

VS中每次改代碼后運行程序不更新,只有重新編譯才生效。

解決方法:將項目移除解決方案,再重新添加進來,即添加->現有項目->選擇.vcxproj文件,即可解決。 轉載于:https://www.cnblogs.com/Gregg/p/11358711.html

socket補充:通信循環、鏈接循環、遠程操作及黏包現象

socket補充:通信循環、鏈接循環、遠程操作及黏包現象 socket通信循環 server端: import socketphone socket.socket(socket.AF_INET,socket.SOCK_STREAM)phone.bind((127.0.0.1,8080))phone.listen(5)conn, client_addr phone.accept() print(conn, cl…

PCA的原理及MATLAB實現

相關文章 PCA的原理及MATLAB實現 UFLDL教程:Exercise:PCA in 2D & PCA and Whitening python-A comparison of various Robust PCA implementations --------&a…

Java生鮮電商平臺-SpringCloud微服務架構中核心要點和實現原理

Java生鮮電商平臺-SpringCloud微服務架構中核心要點和實現原理 說明:Java生鮮電商平臺中,我們將進一步理解微服務架構的核心要點和實現原理,為讀者的實踐提供微服務的設計模式,以期讓微服務在讀者正在工作的項目中起到積極的作用。…

iOS中下載小文件

在iOS中通過網絡下載小文件比如小型圖片等資源,一般在子線程中將數據完全下載完畢,然后在調用block將下載的數據整個部分返回,或者采用同步返回下載數據。 一般采用以下兩種方式: (1)使用GCD將下載操作放…

iOS下載大文件原理解析一

iOS中下載大型文件,需要考慮到占用內存的大小與下載速度(使用多線程),因此本文首先介紹一個原理性下載文件的DEMO。 在下載大型文件中,需要知道下載的進度因此需要使用代理模式,不斷的回調下載進度。 - (…

recv原理、高階版黏包解決方案、基于UDP的socket通信

recv原理、高階版黏包解決方案、基于UDP的socket通信 recv原理 源碼解釋: Receive up to buffersize bytes from the socket. 接收來自socket緩沖區的字節數據, For the optional flags argument, see the Unix manual. 對于這些設置的參數,可…

iOS中下載大型文件的原理解析二

在iOS中下載大型文件,需要使用NSURLConnection 的代理方法: (void)touchesBegan:(NSSet)touches withEvent:(UIEvent *)event { NSURL *url [NSURL URLWithString:”http://d.3987.com/fengj_141112/007.jpg“]; NSURLRequest *request [NSURLReque…

ASP.NET Core Web 應用程序開發期間部署到IIS自定義主機域名并附加到進程調試

想必大家之前在進行ASP.NET Web 應用程序開發期間都有用到過將我們的網站部署到IIS自定義主機域名并附加到進程進行調試。 那我們的ASP.NET Core Web 應用程序又是如何部署到我們的IIS上面進行調試的呢,接下來我們來簡單介紹下: 一、安裝IIS所需的Host擴…