iOS单例模式
單例模式是iOS開發中的一種很常用的開發模式,他的特點是讓某一個類只有一個實例,在項目全局訪問他的時候,他只有一個實例就保證了數據的唯一性。通常用于全局都需要使用的一個實例變量。
下面以定位功能為例,代碼實現功能
1.先創建一個類
GXLocation
?
2.然后聲明一個靜態實例變量
static GXLocation *gxlocation;
?
3.用GCD的一次方法創建一個類的實例
?
+(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;
}
?
創建完成之后,調用的時候就直接調用shareGXlocation方法,就會獲取唯一實例
?
轉載于:https://www.cnblogs.com/yxl-151217/p/10830524.html
總結
- 上一篇: 最简单红米系统一键激活xposed框架教
- 下一篇: Unity初步 基本拼图实现