设为首页 加入收藏

TOP

object-c 以宏的形式定义和实现单例
2014-11-23 21:12:13 来源: 作者: 【 】 浏览:4
Tags: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() 指令防止多个线程同时执行这段代码。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇使用gcc编译C程序 下一篇单片机如何用C申请一个固定地址的..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: