2011-07-29 69 views
0

我已經使用Cocos2d iPhone編寫了幾款遊戲。在我以前的所有遊戲中,我會在設置CCMenu時改變場景,然後在完成時離開該場景。在我目前的項目中,我需要菜單存在於當前場景中,並能夠多次打開然後關閉菜單。由於某種原因,我似乎無法理解,removeChild不會刪除菜單。我在網上看到過使用removeChild顯示的幾個示例,但它不適用於我。下面是我的菜單代碼,當按下Start/CreateNewAccount按鈕時,我希望當前菜單完全從場景中移除。Cocos2d iPhone遊戲從場景中移除菜單

這是在我的init方法中。

 CCMenuItemImage *Start = [CCMenuItemImage itemFromNormalImage:@"MakeLemonade.png" selectedImage:@"MakeLemonadePressed.png" 
                  target:self 
                 selector:@selector(CreateNewAccount:)]; 
    CCMenuItemImage *About = [CCMenuItemImage itemFromNormalImage:@"About.png" selectedImage:@"AboutPressed.png" 
                  target:self 
                  selector:@selector(About:)]; 
    Start.position = ccp(-175, -90); 
    About.position = ccp(175, -90); 

    CCMenu *MainMenu = [CCMenu menuWithItems: Start, About, nil]; 
    [Start runAction:[CCFadeIn actionWithDuration:1.0]]; 
    [About runAction:[CCFadeIn actionWithDuration:1.0]]; 
    [self addChild:MainMenu z:6]; 

} 
return self; 
} 
-(void) BeginMenuLayer { 

//this is not working 


[self removeChild:MainMenu cleanup:YES]; 

} 

回答

1

在您的init方法中,您已將MainMenu聲明爲局部變量。您並未將其設置爲屬性,因此您稍後將其刪除時沒有參考。

1)確保已聲明的屬性爲這樣的:

@property (nonatomic, retain) CCMenu *MainMenu; 

2)在你的實現上合成它:

@synthesize MainMenu; 

3)確保你釋放在你的dealloc:

-(void)dealloc { 
    self.MainMenu = nil; 
    [super dealloc]; 
} 

4)當你構建它,把它分配給你的財產,而不是當地的雜物ble:

self.MainMenu = [CCMenu menuWithItems: Start, About, nil]; 

現在您保留了該對象的引用,您可以稍後將其傳遞給。

+0

您不需要將其設置爲屬性。一個iVar就足夠了。只是想我會澄清這一點。 – EmilioPelaez

+0

這是真的。它只是需要額外的努力,以避免在做伊娃分配時泄漏內存。 – cduhn

+0

哦,就是這樣,謝謝你的幫助! – user597136