前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >单例对象

单例对象

作者头像
用户1219438
发布2018-02-01 15:11:48
5600
发布2018-02-01 15:11:48
举报
文章被收录于专栏:AliceAliceAlice

在开发中经常需要使用单例对象。今天主要说的是单例宏

首先先简单介绍一下

1.单例设计模式(Singleton)

1> 什么: 它可以保证某个类创建出来的对象永远只有1个

2> 作用(为什么要用)

* 节省内存开销

* 如果有一些数据, 整个程序中都用得上, 只需要使用同一份资源(保证大家访问的数据是相同的,一致的)

* 一般来说, 工具类设计为单例模式比较合适

3> 怎么实现

* MRC(非ARC)

* ARC

代码采用的是mrc的环境

单独创建一个.h文件 例如SingleTon.h

 1 //帮助实现单例设计模式
 2 /*
 3  alloc方法内部会调用allocWithZone
 4  */
 5 
 6 #define SingletonH(methodName) +(instancetype)shared##methodName;
 7 
 8 #if __has_feature(objc_arc)//是arc
 9 
10 #define SingletonM(methodName)\
11 static id _instance = nil;\
12 \
13 +(instancetype)allocWithZone:(struct _NSZone *)zone\
14 {\
15     \
16     if(_instance == nil)\
17     {\
18         static dispatch_once_t onceToken;\
19         dispatch_once(&onceToken, ^{\
20             _instance = [super allocWithZone:zone];\
21         });\
22     }\
23     return _instance;\
24 }\
25 +(instancetype)shared##methodName\
26 {\
27     return [[self alloc]init];\
28 }\
29 
30 #else//不是arc
31 
32 #define SingletonM(methodName)\
33 static id _instance = nil;\
34 \
35 +(instancetype)allocWithZone:(struct _NSZone *)zone\
36 {\
37 \
38 if(_instance == nil)\
39 {\
40 static dispatch_once_t onceToken;\
41 dispatch_once(&onceToken, ^{\
42 _instance = [super allocWithZone:zone];\
43 });\
44 }\
45 return _instance;\
46 }\
47 -(oneway void)release\
48 {\
49 \
50 }\
51 \
52 -(instancetype)retain\
53 {\
54 return self;\
55 }\
56 -(NSUInteger)retainCount\
57 {\
58 return 1;\
59 }\
60 +(instancetype)shared##methodName\
61 {\
62 return [[self alloc]init];\
63 }
64 
65 #endif

\代表的含义是说:下一行属于它  

然后在使用的时候

soundTool.h文件

#import <Foundation/Foundation.h>
#import "singleTon.h"
@interface soundTool : NSObject
SingletonH(sound)
@end

 soundTool.m文件

#import "soundTool.h"

@implementation soundTool
//注意里边的方法名不要跟类名相同(大小写都不行得)
SingletonM(sound)

@end

然后在controller.m文件中

- (void)viewDidLoad {
    [super viewDidLoad];
    dataTool *d1 = [dataTool shareddatatools];
    dataTool *d2 = [dataTool shareddatatools];
    soundTool *s1 = [soundTool sharedsound];
    soundTool *s2 = [soundTool sharedsound];
    NSLog(@"%p %p ",d1,d2);
    NSLog(@"%p %p ",s1,s2);

 这样就能报保证多个类都是单例的

有时候 出现mrc 跟arc 混编的状况  

这样的话在个别的文件  的配置文件中追加 -fobjc-arc (说明是arc文件)

还有时候可能碰见这样的代码

 //补充
    NSArray *array = [[NSArray alloc]init];
    //判断如果不是arc状态的话  进行array的释放
    #if !__has_feature(objc_arc)
        [array release];
    #endif

 这个说明判断如果不是arc环境的话 就要对array进行释放

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-11-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档