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)