Objective-C 单例宏
#define SINGLETON_SHARED + (instancetype)shared;
#define SINGLETON_METHOD(ClassName) \
+ (id)allocWithZone:(struct _NSZone *)zone { \
static ClassName *_shared = nil;\
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_shared = [super allocWithZone:zone]; \
}); \
return _shared; \
} \
\
+ (instancetype)shared { \
return [[[self class] alloc] init];\
}
Swift 单例声明
class Singleton {
// 单例 shared
static let shared = Singleton()
// 私有init
private init(){}
}
// 继承自 NSObject
class SingletonObject: NSObject {
// 单例 shared
static let shared = SingletonObject()
// 私有init
private override init() {}
// 不操作返回本身
override func copy() -> Any {
return self
}
// 不操作返回本身
override func mutableCopy() -> Any {
return self
}
}