iOS的单例模式

查看了网上十多个人的资料,整理了一下。

1,单例有两种模式,一种为懒汉模式,一种为饿汉模式。饿汉模式需要在引入头文件时就加载单例,所以,我们不建议使用这种方式。

2,单例有两种写法,一种是GCD,一种是根据懒加载和线程锁的方式加载。(gcd方式写单例可以不考虑线程安全问题,本文也这么写)。

话不多说,上代码!

1.创建单例类

1.1 在.h中定义属性和创建方法

1.2 在.m中实现


2.宏定义单例

// .h文件


#define SingletonH(name) + (instancetype)shared##name;

// .m文件

#define SingletonM(name) \

static id _instance; \

\

+ (instancetype)allocWithZone:(struct _NSZone *)zone \

{ \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

_instance = [super allocWithZone:zone]; \

}); \

return _instance; \

} \

\

+ (instancetype)shared##name \

{ \

_instance = [[self alloc] init]; \

return _instance; \

} \

\

-(instancetype)init{\

static dispatch_once_t onceToken;\

dispatch_once(&onceToken, ^{\

_instance = [super init];\

});\

return _instance;\

}\

\

+(id)copyWithZone:(struct _NSZone *)zone{\

return _instance;\

}\

\

-(id)copyWithZone:(NSZone *)zone{\

return _instance;\

}\

\

+(id)mutableCopyWithZone:(struct _NSZone *)zone{\

return _instance;\

}\

\

-(id)mutableCopyWithZone:(NSZone *)zone{\

return _instance;\

}

然后创建单例类,在.h和.m中分别加入两个宏,传入参数

//.h类

//引入这个宏文件

#import "Singleton.h"

@interface StudentManager : NSObject

SingletonH(StudentManager)

@end

//.m类

@implementation StudentManager

SingletonM(StudentManager)

@end


在试图控制器中使用单例时,引入单例类头文件后直接用类名调用share+类名就行

#import

#import"StudentManager.h"

intmain(intargc,constchar* argv[]) {

@autoreleasepool{

// insert code here...

NSLog(@"Hello, World!");

[StudentManager sharedsingleton];

}

return0;

}

你可能感兴趣的:(iOS的单例模式)