Objective-c之Singletone模式

1,早期的Objective-c并没有ARC,有人写了SynthesizeSingleton.h并定义宏

SYNTHESIZE_SINGLETON_FOR_CLASS_HEADER和SYNTHESIZE_SINGLETON_FOR_CLASS。

但现在在开启了ARC的工程中那样的代码并不能通过编译。

下面介绍通过dispatch_once实现并与ARC兼容的单例模式

MyARCSingletonClass.h

#import <Foundation/Foundation.h>

@interface MyARCSingletonClass : NSObject

/**
 Warning: dispatch_once is not reentrant
 Don't make a recursive call to sharedInstance from inside the dispatch_once block.
 */
+(MyARCSingletonClass *)sharedInstance;

//禁用alloc,init,new
+(instancetype) alloc __attribute__((unavailable("alloc not available, call sharedInstance instead")));
-(instancetype) init __attribute__((unavailable("init not available, call sharedInstance instead")));
+(instancetype) new __attribute__((unavailable("new not available, call sharedInstance instead")));

@end

代码很简单,不做解释。

还可以将这种实现模式定义为通用的宏

singletone.h

#import <Foundation/Foundation.h>

#ifndef Singleton_singletone_h
#define Singleton_singletone_h

#define DECLARE_SINGLETON(className) \
@interface className : NSObject \
+(className *)sharedInstance; \
+(instancetype) alloc __attribute__((unavailable("alloc not available, call sharedInstance instead"))); \
-(instancetype) init __attribute__((unavailable("init not available, call sharedInstance instead"))); \
+(instancetype) new __attribute__((unavailable("new not available, call sharedInstance instead"))); \
@end

#define IMPLEMENT_SINGLETON(className) \
@implementation className\
+(className *)sharedInstance { \
    static dispatch_once_t pred; \
    static className *shared = nil; \
    dispatch_once(&pred, ^{ \
        shared = [[super alloc] initUniqueInstance]; \
    }); \
    return shared; \
} \
-(instancetype) initUniqueInstance { \
    return [super init]; \
} \
@end

MyARCSingletonClass.h

#import "singletone.h"

DECLARE_SINGLETON(MyARCSingletonClass)

MyARCSingletonClass.m

IMPLEMENT_SINGLETON(MyARCSingletonClass)




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值