單例模式在ios開發中是最為常用的模式之一,在應用這個模式時,單例物件的類必須保證只有乙個例項存在。許多時候整個系統只需要擁有乙個的全域性物件,這樣有利於我們協調系統整體的行為。一般情況下,許多人都是按下面的方式寫單例模式:
#import "singleton.h"
@implementation
singleton
static singleton *sharesingleton = nil;
+ (instancetype)sharesingleton );
return sharesingleton;
}@end
測試一下這種方法可行不:
singleton *one = [singleton sharesingleton];
nslog(@"one = %@", one);
singleton *two = [singleton sharesingleton];
nslog(@"two = %@", two);
singleton *three = [[singleton alloc] init];
nslog(@"three = %@", three);
控制台輸出內容:
2015-12-22 15:31:38.230 singleton[2264:1996979] one =
2015-12-22 15:31:38.230 singleton[2264:1996979] two =
2015-12-22 15:31:38.231 singleton[2264:1996979] three =
由此可見,只有呼叫sharesingleton方法獲得的物件是相通的,用alloc init來構造物件的時候,得到的確實不一樣的結果。究其原因,當使用alloc init建立物件時,在呼叫alloc方法時,oc內部會呼叫allocwithzone這個方法來申請記憶體,為了避免allocwithzone申請新的記憶體,可以重寫allocwithzone方法,在該方法中呼叫sharesingleton方法返回單例物件。拷貝物件也是同樣的道理。
完整**如下:
#import "singleton.h"
@implementation
singleton
static singleton *sharesingleton = nil;
+ (instancetype)sharesingleton );
return sharesingleton;
}+ (instancetype)allocwithzone:(struct _nszone *)zone
- (id)copywithzone:(struct _nszone *)zone
@end
測試:
singleton *one = [singleton sharesingleton];
nslog(@"one = %@", one);
singleton *two = [singleton sharesingleton];
nslog(@"two = %@", two);
singleton *three = [[singleton alloc] init];
nslog(@"three = %@", three);
singleton *four = [[singleton alloc] init];
nslog(@"four = %@", [four copy]);
singleton *five = [singleton new];
nslog(@"five = %@", five);
結果:
2015-12-22 17:01:52.350 singleton[2399:2262945] one =
2015-12-22 17:01:52.350 singleton[2399:2262945] two =
2015-12-22 17:01:52.351 singleton[2399:2262945] three =
2015-12-22 17:01:52.351 singleton[2399:2262945] four =
2015-12-22 17:01:52.351 singleton[2399:2262945] five =
完整單例模式的寫法
ios單例模式 singleton 單例模式的意思就是只有乙個例項。單例模式確保某乙個類只有乙個例項,而且自行例項化並向整個系統提供這個例項。這個類稱為單例類。1.單例模式的要點 顯然單例模式的要點有三個 一是某個類只能有乙個例項 二是它必須自行建立這個例項 三是它必須自行向整個系統提供這個例項。2...
iOS 單例的寫法
關於什麼是單例,ios中的單例模式是什麼,自行爬頁搜尋。這裡拋磚引玉,說說單例模式應該怎樣實現。直接上 singleton.h singletondemo created by wangbo on 3 9 16.import inte ce singleton nsobject instancety...
單例的寫法
1.import mysingleton.h static mysingleton singleton nil id shareobject synchronized self if singleton nil singleton mysingleton alloc init return sing...