美文网首页
iOS的单例模式

iOS的单例模式

作者: touch释然 | 来源:发表于2017-10-17 18:03 被阅读0次

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

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单例模式iOS之单例模式初探iOS单例详解

  • iOS 单例模式

    关于单例模式的详解,看完这几篇,就完全了然了。iOS 单例模式iOS中的单例模式iOS单例的写法

  • iOS 单例模式 or NSUserDefaults

    本文内容:iOS的单例模式NSUserDefaults的使用总结:iOS单例模式 and NSUserDefaul...

  • 单例模式 Singleton Pattern

    单例模式-菜鸟教程 iOS中的设计模式——单例(Singleton) iOS-单例模式写一次就够了 如何正确地写出...

  • 【设计模式】单例模式

    学习文章 iOS设计模式 - 单例 SwiftSingleton 原理图 说明 单例模式人人用过,严格的单例模式很...

  • iOS模式设计之--创建型:1、单例模式

    iOS模式设计之--1、单例模式

  • iOS单例模式容错处理

    ios 单例模式容错处理 1、单例模式的使用和问题解决 在ios开发的过程中,使用单例模式的场景非常多。系统也有很...

  • 谈一谈iOS单例模式

    这篇文章主要和大家谈一谈iOS中的单例模式,单例模式是一种常用的软件设计模式,想要深入了解iOS单例模式的朋友可以...

  • iOS知识梳理3:设计模式

    iOS有哪些常见的设计模式?单例模式/委托模式/观察者模式/MVC模式 单例模式 单例保证了应用程序的生命周期内仅...

  • 单例对象

    iOS单例模式(Singleton)单例模式的意思就是:只有一个实例;单例模式确保每个类只有一个实例,而且自行实例...

网友评论

      本文标题:iOS的单例模式

      本文链接:https://www.haomeiwen.com/subject/guhpjxtx.html