单例的实现
第一种常规的方法
static MyClass *myClass = nil;
- (MyClass *)sharedInstance
{
if(!myClass) myClass = [[self alloc] init];
return myClass;
}
第二种方法,ios4以后可以使用GCD的dispatch_once来帮助实现
+(MyClass *)shareInstance
{
static MyClass *myClass = nil;
static dispatch_once_t predicate;
dispath_once(&predicate, ^{
myClass = [[self alloc] init];
});
return myClass;
}
现在一般的单例实现都使用宏定义的方式
#undef AS_SINGLETON
#define AS_SINGLETON( __class ) \
+ (__class *)sharedInstance;
#undef DEF_SINGLETON
#define DEF_SINGLETON( __class ) \
+ (__class *)sharedInstance \
{ \
static dispatch_once_t once; \
static __class * __singleton__; \
dispatch_once( &once, ^{ __singleton__ = [[__class alloc] init]; } ); \
return __singleton__; \
}