cocos2d: 使用半單例
把MultiLayerScene設置成半單例,目的是讓別的對象可以直接訪問MultiLayerScene
- static MultiLayerScene* multiLayerSceneInstance;
-
- +(MultiLayerScene*) sharedLayer
- {
- NSAssert(multiLayerSceneInstance != nil, @"MultiLayerScene not available!");
- return multiLayerSceneInstance;
- }
-
- //初始化MultiLayerScene
- -(id) init
- {
- if ((self = [super init]))
- {
- multiLayerSceneInstance = self;
- // GameLayer層
- GameLayer* gameLayer = [GameLayer node];
- [self addChild:gameLayer z:1 tag:LayerTagGameLayer];
-
- }
- return self;
- }
-
- -(void) action1
- {
- // do something
- }
-
- -(void) dealloc
- {
- multiLayerSceneInstance = nil;
-
- // don't forget to call "super dealloc"
- [super dealloc];
- }
訪問半單例方法,如在GameLayer層中可以這樣訪問MultiLayerScene中的action1方法:
- [[MultiSceneLayer shareLayer] action1];
半單例與普通的單例類不同,任何時候只存在一個MultiLayerScene的實例,它不能被用來初始化MultiLayerScene。