單例模式atom
屬性spa
代理代理
通知code
某個類只產生一個對象,且是一個全局對象,之後每次建立該類對象時,只會獲得第一次建立的那個類對象。orm
因此,能夠用於在多視圖場景下傳遞參數,原理以下圖所示。對象
與C++不同,使用ObjectiveC建立單例類的時候,須要注意:繼承
首先必須建立一個全局實例,一般存放在一個全局變量中,此全局變量設置爲nil生命週期
須要重寫+allocWithZone:方法,防止經過標準的alloc方式建立新的實例string
須要重寫-copyWithZone方法,防止經過copy方法獲得新的實例it
須要重寫-mutableCopyWithZone:方法,防止經過copy方法獲得新的實例
示例以下:
Singleton.h
@interface Singleton : NSObject <NSCopying, NSMutableCopying> @property (strong, nonatomic)NSString *value; //該屬性能夠被不一樣視圖使用,傳值依據 //單例方法 + (id)shareSingleton; @end
其中,繼承NSCopying和NSMutableCopying協議是爲了重寫copyWithZone和mutableCopyWithZone方法
Singleton.m
static Singleton *instance = nil; //存在於整個程序生命週期 #pragma mark 單例方法 + (id)shareSingleton{ if (nil == instance) { instance = [[Singleton alloc]init]; } return instance; } //重寫allocWithZone:方法,防止經過標準的alloc方式建立新的實例 +(instancetype)allocWithZone:(struct _NSZone *)zone{ if (nil == instance) { instance = [[super allocWithZone:zone]init]; } return instance; } //重寫copyWithZone:方法,防止經過copy方法獲得新的實例 -(id)copyWithZone:(NSZone *)zone{ return self; } //重寫mutableCopyWithZone:方法,防止經過copy方法獲得新的實例 -(id)mutableCopyWithZone:(NSZone *)zone{ return self; }
在A視圖中賦值
//獲取導航欄的大小 CGRect rectNav = nav.navigationBar.frame; //單例模式保存導航欄的高度 Singleton *singe = [Singleton shareSingleton]; singe.value = [NSString stringWithFormat:@"%f", rectNav.size.height];
在B視圖中使用
Singleton *single = [Singleton shareSingleton]; CGRect frame = CGRectMake(0, 5+single.value.floatValue, self.frame.size.width, 200);