您的位置:首页 > 其它

多线程学习12-GCD实现单例模式

2016-04-20 14:51 176 查看
学习多线程12(之前跟着小码哥视频学习了多线程,准备把学到的东西放到网上,便于参考。仅有视频,所以所有文字都是自己打的,同时也温习一下多线程)

单例模式

单例模式的作用

可以保证在程序运行过程中,一个类只有一个实例,而且该实例易于供外界访问。

LMPerson.h

#import <Foundation/Foundation.h>

@interface LMPerson : NSObject
+(instancetype)shareInstance;

@end


LMPerson.m

#import "LMPerson.h"
@interface LMPerson()<NSCopying>

@end
@implementation LMPerson
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;
}
@end
博客原地址:/article/11543095.html

也可以单独抽出来放在一个头文件中,每次使用只需要导入该头文件即可

#ifndef LMSingleton_h
#define LMSingleton_h

//.h文件
#define LMSingletonH +(instancetype)shareInstance;
//.m文件
#define LMSingletonM \
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;\
}

#endif /* LMSingleton_h */


至此,关于多线程的基本知识点,已结束。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: