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