我有一個CCLayer,我想添加許多按鈕。 我創建了MyButton類與此初始化函數:將cclayer傳遞給我的對象時的內存問題
-(id) initWithLayer:(MyLayer *)theLayer andDictionary:(NSDictionary *)data {
self = [super init];
if (self != nil)
{
self.layer = theLayer;
self.tag = [[data objectForKey:@"day"] intValue];
_layerZ = [[data objectForKey:@"z"] intValue];
_closedCard = [[CCSprite alloc] initWithFile:[data objectForKey:@"file"]];
_openedCardFile = [[NSString alloc] initWithString:[data objectForKey:@"open_card"]];
CCMenuItemImage *itemImage = [CCMenuItemImage
itemFromNormalSprite:_closedCard
selectedSprite:nil
target:self
selector:@selector(displayCard:)];
CGPoint position = CGPointFromString([data objectForKey:@"position"]);
_position = ccp(position.x, position.y);
itemImage.position = _position;
itemImage.tag = self.tag;
_theCardButton = [CCMenu menuWithItems:itemImage, nil];
_theCardButton.position = CGPointZero;
[self.layer addChild:_theCardButton z:_layerZ];
}
return self;
}
此初始化函數將按鈕添加到該層,我在myButton的管理所有的行爲(運動圖像的變化)類。
所以圖層被髮送到所有的MyButton實例。直到每個按鈕被釋放後,圖層纔會調用dealloc方法。
這些按鈕正在通過陣列添加到層:
_buttons = [[NSMutableArray alloc] init];
for (NSDictionary *buttonData in buttonsArray) {
MyButton *btn = [[MyButton alloc] initWithLayer:self andDictionary:buttonData];
[_buttons addObject:btn];
[btn release];
}
我的問題是,當我替換此場景,則myButton的的dealloc methos不被調用和存儲器不被釋放,導致[_buttons發佈]位於圖層的dealloc方法中,該方法不會被調用,因爲圖層已傳遞到每個按鈕。
這是一團糟。任何人都可以告訴我解決這個內存問題的最佳方法嗎?
- 編輯
如果我嘗試調用replaceScene前手動釋放按鈕的陣列,每個按鈕調用的dealloc,但後來我得到這個錯誤信息:
[CCMenu pauseSchedulerAndActions]: message sent to deallocated instance 0x131a0670
您創建了一個保留週期。在init中不要傳入圖層。如果圖層是節點的父級,則可以使用父級屬性。在所有其他情況下,考慮將圖層設置爲單例類。 – LearnCocos2D 2012-07-11 15:39:40