我用cocos2d version2.0建游戏,没用ARC,发现一个问题:单例无效。
我用了两个单例宏,问题一样。
#ifndef SINGLETON_INTERFACE
#define SINGLETON_INTERFACE(CLASSNAME) \
+(CLASSNAME*) sharedManager;
#endif
#ifndef SINGLETON_IMPLEMENTATION
#define SINGLETON_IMPLEMENTATION(CLASSNAME) \
\
+(CLASSNAME*) sharedManager { \
static dispatch_once_t pred; \
static CLASSNAME* shared##CLASSNAME = nil; \
dispatch_once( &pred, ^{ \
shared##CLASSNAME = [[self alloc] init]; }); \
return shared##CLASSNAME; \
}
#endif
或者
#ifndef SINGLETON_INTERFACE
#define SINGLETON_INTERFACE(CLASSNAME) \
+(CLASSNAME*) sharedManager;
#endif
#ifndef SINGLETON_IMPLEMENTATION
#define SINGLETON_IMPLEMENTATION(CLASSNAME) \
\
static CLASSNAME* shared##CLASSNAME = nil; \
\
+(CLASSNAME*) sharedManager \
{ \
if (shared##CLASSNAME != nil) { \
return 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; \
} \
} \
NSAssert(NO, @ "[" #CLASSNAME " alloc] explicitly called on singleton class."); \
return nil; \
} \
\
-(id) copyWithZone:(NSZone*)zone \
{ \
return self; \
} \
\
-(id) retain \
{ \
return self; \
} \
\
-(unsigned) retainCount \
{ \
return UINT_MAX; \
} \
\
-(oneway void) release \
{ \
} \
\
-(id) autorelease \
{ \
return self; \
}
#endif
利用:
[[CCDirector sharedDirector] replaceScene:[MenuScene sharedManager]];
MenuScene 再次显示,但任何按钮(CCMenu)或其他元素(CCNode)都没有响应。我的意思是第一次调用,场景一切正常,再次调用时,场景显示但菜单或其他元素没有响应。但是在cocos2d v1.0 运行非常好。
///////////////////////////////////////// ///////////////
我在没有“[super cleanup]”的情况下覆盖了“cleanup”,如下所示:
-(void) dealloc
{
[super cleanup];
[super dealloc];
}
-(void) cleanup
{
//
}
现在,运行单例的场景没问题,但它安全吗?