Singleton.h 513 B

1234567891011121314151617181920212223242526
  1. // .h
  2. #define singleton_interface(class) + (instancetype)shared##class;
  3. // .m
  4. #define singleton_implementation(class) \
  5. static class *_instance; \
  6. \
  7. + (id)allocWithZone:(struct _NSZone *)zone \
  8. { \
  9. static dispatch_once_t onceToken; \
  10. dispatch_once(&onceToken, ^{ \
  11. _instance = [super allocWithZone:zone]; \
  12. }); \
  13. \
  14. return _instance; \
  15. } \
  16. \
  17. + (instancetype)shared##class \
  18. { \
  19. if (_instance == nil) { \
  20. _instance = [[class alloc] init]; \
  21. } \
  22. \
  23. return _instance; \
  24. }