一:创建 宏 文件 SynthesizeSingleton.h

SynthesizeSingleton.h

#if __has_feature(objc_arc) // ARC Version

#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname)   \
\
+ (classname *)shared##classname\
{\
    static classname *shared##classname = nil;\
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
        shared##classname = [[classname alloc] init];\
    });\
    return shared##classname;\
}

#else // Non-ARC Version

#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

  二:使用

MyClass.h

@interface MyClass : NSObject

+(DataStorage *)sharedMyClass;

@end
MyClass.m

#import "SynthesizeSingleton.h"
@implementation MyClass
SYNTHESIZE_SINGLETON_FOR_CLASS(MyClass)
@end

 参考资料

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-13
猜你喜欢
  • 2022-12-23
  • 2021-10-15
  • 2022-12-23
  • 2022-12-23
  • 2021-06-28
  • 2021-11-18
  • 2022-12-23
相关资源
相似解决方案