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

来源:互联网 发布:公务员 知乎 编辑:程序博客网 时间:2024/06/09 15:44

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

单例模式

单例模式的作用

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

LMPerson.h

#import <Foundation/Foundation.h>@interface LMPerson : NSObject+(instancetype)shareInstance;@end

LMPerson.m

#import "LMPerson.h"@interface LMPerson()<NSCopying>@end@implementation LMPersonstatic 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
博客原地址:http://blog.csdn.net/leemin_ios/article/details/51200068
也可以单独抽出来放在一个头文件中,每次使用只需要导入该头文件即可

#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 */

至此,关于多线程的基本知识点,已结束。

0 0
原创粉丝点击