iOS单例模式
單例模式是iOS開發(fā)中的一種很常用的開發(fā)模式,他的特點(diǎn)是讓某一個(gè)類只有一個(gè)實(shí)例,在項(xiàng)目全局訪問他的時(shí)候,他只有一個(gè)實(shí)例就保證了數(shù)據(jù)的唯一性。通常用于全局都需要使用的一個(gè)實(shí)例變量。
下面以定位功能為例,代碼實(shí)現(xiàn)功能
1.先創(chuàng)建一個(gè)類
GXLocation
?
2.然后聲明一個(gè)靜態(tài)實(shí)例變量
static GXLocation *gxlocation;
?
3.用GCD的一次方法創(chuàng)建一個(gè)類的實(shí)例
?
+(instancetype) shareGXlocation
{
? ? static dispatch_once_t onceToken;
? ? dispatch_once(&onceToken, ^{
? ? ? ? gxlocation = [[self alloc] init];
? ? });
? ? return gxlocation;
}
?
3.重寫allocWithZone方法
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
? ? static dispatch_once_t onceToken;
? ? dispatch_once(&onceToken, ^{
? ? ? ? if (gxlocation == nil) {
? ? ? ? ? ? gxlocation = [super allocWithZone:zone];
? ? ? ? }
? ? });
? ? return gxlocation;
}
?
-(id)copyWithZone:(NSZone *)zone
{
? ? return gxlocation;
}
?
-(id)mutableCopyWithZone:(NSZone *)zone
{
? ? return gxlocation;
}
?
創(chuàng)建完成之后,調(diào)用的時(shí)候就直接調(diào)用shareGXlocation方法,就會(huì)獲取唯一實(shí)例
?
轉(zhuǎn)載于:https://www.cnblogs.com/yxl-151217/p/10830524.html
總結(jié)
- 上一篇: 最简单红米系统一键激活xposed框架教
- 下一篇: Unity初步 基本拼图实现