美文网首页
oc单例的快速创建

oc单例的快速创建

作者: 程序疯 | 来源:发表于2018-01-31 09:02 被阅读0次

oc工程中 都会用到单例模式进行应用中数据的存储,然而在创建单例的过程会比较的繁琐 需要区分MRC 与ARC 给大家分享一个快速的方法 直接上代码 

#if __has_feature(objc_arc)

#define     MYOBJECT_SINGLETON_FOR_CLASS(classname) \

\

static classname *shared##classname = nil; \

\

+ (classname *)shared##classname \

{ \

@synchronized(self) \

{ \

if (shared##classname == nil) \

{ \

shared##classname = [[self alloc] init]; \

} \

} \

\

return shared##classname; \

} \

\

+ (id)allocWithZone:(NSZone *)zone \

{ \

@synchronized(self) \

{ \

if (shared##classname == nil) \

{ \

shared##classname = [super allocWithZone:zone]; \

return shared##classname; \

} \

} \

\

return nil; \

} \

\

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

{ \

return self; \

} \

#else

#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \

\

static classname *shared##classname = nil; \

\

+ (classname *)shared##classname \

{ \

@synchronized(self) \

{ \

if (shared##classname == nil) \

{ \

shared##classname = [[self alloc] init]; \

} \

} \

\

return shared##classname; \

} \

\

+ (id)allocWithZone:(NSZone *)zone \

{ \

@synchronized(self) \

{ \

if (shared##classname == nil) \

{ \

shared##classname = [super allocWithZone:zone]; \

return shared##classname; \

} \

} \

\

return nil; \

} \

\

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

{ \

return self; \

} \

\

- (id)retain \

{ \

return self; \

} \

\

- (NSUInteger)retainCount \

{ \

return NSUIntegerMax; \

} \

\

- (oneway void)release \

{ \

} \

\

- (id)autorelease \

{ \

return self; \

}

#endif

相关文章

  • iOS - 单例创建

    Swift创建单例 代码如下:Swift5 对应OC创建单例

  • oc单例的快速创建

    oc工程中 都会用到单例模式进行应用中数据的存储,然而在创建单例的过程会比较的繁琐 需要区分MRC 与ARC 给大...

  • iOS Swift中如何创建单例

    单例就是该类在系统中只有一个实例,对比一下OC的单例创建方式来看一下Swift的单例是如何写的。 OC中的单例是这...

  • 单例模式的书写

    ARC OC 中的单例 根据OC单例 改写成 Swift 中的单例 OC调用swift,需要#import "单例...

  • Swift的四种传值方法

    Swift中常用的四种传值方法:单例,单例,闭包(相当于OC的block传值),通知 1单例: 1>.创建单例变量...

  • OC-多线程-单例模式

    OC-多线程-单例模式 说起单例,我们一般使用GCD的dispath_once来创建单例 对于单例,需要知道以下两...

  • swiftly单例

    swiftly的单例比OC的更加简单! Oc中的单例:

  • iOS模式解析-单例模式

    设计模式-单例模式 1、为什么用单例模式 1.1、OC编程习惯 xcode 4.2之前使用MRCalloc创建的对...

  • iOS开发之进阶篇(5)—— 单例

    目录 最终推荐写法 何为单例? 对象的创建 单例写法的讨论过程 1. 最终推荐写法 1.1 OC SingleOb...

  • iOS OC创建单例(Singleton)

    昨天总结了swift的单例创建模式,今天总结一下OC单例的创建模式,本人才疏学浅,如有错误之处,还望大家指出。 创...

网友评论

      本文标题:oc单例的快速创建

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