单例模式的作用:可以保证在程序运行过程,一个类只有一个实例,而且这个实例易于供外界访问。永远只分配一次内存给这个类。由于在调用alloc方法的时候,都会调用allocWithZone,所以要重写这个方法,保证只分配一次内存。 dispatch_once这个方法可以保证只调用一次,并且会自动加锁,线程安全。
在6.0之前的版本中修改工程为非ARC
OC 设计模式——单例模式

Xcode6.3下设置,修改工程在非ARC下:

OC 设计模式——单例模式

定义宏来实现单例的通用性。在拼接宏的时候不能使用注释。最后面不能加/.

// ## : 两个#号连接字符串和参数
#define singleton_h(name) + (instancetype)shared##name;

#define singleton_m(name) \
static id _instance; \
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        _instance = [super allocWithZone:zone]; \
    }); \
    return _instance; \
} \
 \
+ (instancetype)shared##name \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        _instance = [[self alloc] init]; \
    }); \
    return _instance; \
} \
 \
- (oneway void)release \
{ \
 \
} \
 \
- (id)autorelease \
{ \
    return _instance; \
} \
 \
- (id)retain \
{ \
    return _instance; \
} \
 \
- (NSUInteger)retainCount \
{ \
    return 1; \
} \
 \
+ (id)copyWithZone:(struct _NSZone *)zone \
{ \
    return _instance; \
}

调用举例:

- (id)init

{

    if (self = [super init]) {

        static dispatch_once_t onceToken;

        dispatch_once(&onceToken, ^{

            // 加载资源

            

        });

    }

    return self;

}

 

singleton_m(NetTool)

重写init方法。调用单例的宏。

 

 

如何实现ARC与非ARC下的单例宏,兼容?(添加条件编译进行判断)

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-04-15
  • 2021-06-02
  • 2021-12-31
猜你喜欢
  • 2021-09-13
  • 2021-12-15
  • 2021-08-01
  • 2021-12-10
  • 2022-12-23
相关资源
相似解决方案