iOS 开发

单例模式

2016-03-23  本文已影响32人  流行的武

#创建一个单例3步1.在需要创建单例的类中 #import"HWSingleton.h" ,导入头文件2.在.h 文件中  加入代码 HWSingletonM3.在.m 文件中  加入代码 HWSingletonH--------------- 我是分割线 --------------## Dog.h``` #import#import "HWSingleton.h" @interface Dog : NSObject HWSingletonH @end.```## Dog.m```#import "Dog.h"@interface Dog ()@end

@implementation Dog

HWSingletonM

@end

```

懵逼了吧, HWSingleton.h里到底是啥?

其实里面就是两个宏,直接上代码

# HWSingleton.h中的代码

```

// .h文件

#define HWSingletonH  + (instancetype)shareInstance;

// .m文件

#define HWSingletonM \

\

static id _instance;\

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

\

static dispatch_once_t onceToken;\

dispatch_once(&onceToken, ^{\

_instance = [super allocWithZone:zone];\

});\

return _instance;\

}\

\

+ (instancetype)shareInstance{\

static dispatch_once_t onceToken;\

dispatch_once(&onceToken, ^{\

_instance = [[self alloc]init];\

});\

return _instance;\

}\

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

return _instance;\

}

```

上一篇 下一篇

猜你喜欢

热点阅读