object-cマクロの形式で単例を定義し実現する


宣言と実装:
	#undef	AS_SINGLETON
	#define AS_SINGLETON( __class ) \
			- (__class *)sharedInstance; \
			+ (__class *)sharedInstance;

	#undef	DEF_SINGLETON
	#define DEF_SINGLETON( __class ) \
			- (__class *)sharedInstance \
			{ \
				return [__class sharedInstance]; \
			} \
			+ (__class *)sharedInstance \
			{ \
				static dispatch_once_t once; \
				static __class * __singleton__; \
				dispatch_once( &once, ^{ __singleton__ = [[[self class] alloc] init]; } ); \
				return __singleton__; \
			}

	#undef	DEF_SINGLETON_AUTOLOAD
	#define DEF_SINGLETON_AUTOLOAD( __class ) \
			- (__class *)sharedInstance \
			{ \
				return [__class sharedInstance]; \
			} \
			+ (__class *)sharedInstance \
			{ \
				static dispatch_once_t once; \
				static __class * __singleton__; \
				dispatch_once( &once, ^{ __singleton__ = [[[self class] alloc] init]; } ); \
				return __singleton__; \
			} \
			+ (void)load \
			{ \
				[self sharedInstance]; \
			}

次の操作を行います.
XXです.hヘッダファイルでは、次のように宣言します.
AS_SINGLETON(MainVC)

XXです.mファイルでは、次のように実現されます.
DEF_SINGLETON(MainVC)

ここでは単一スレッドのコードを示し,マルチスレッドであれば@synchronizer()命令を用いて複数のスレッドが同時にこのコードを実行することを防止できる.