【发布时间】:2009-10-17 00:57:52
【问题描述】:
我正在开发我的第一个应用程序,并且有一些关于内存管理的问题。
第一个问题:
我正在制作一个像这样的介绍场景
#import "Intro_Scene.h"
#import "Main_Menu.h"
#import "Label.h"
@implementation Intro_Scene
@synthesize logo,label;
-(id) init
{
self = [super init];
if(self != nil)
{
//Load logo image and set position
logo = [Sprite spriteWithFile:@"AVlogo_1.png"];
logo.position = ccp(-50, 0);
logo.scale = 1.8f;
[self addChild: logo];
//Creates 3 actions for the logo sprite
id action0 = [MoveTo actionWithDuration:0 position:ccp(160,270)];
id action1 = [FadeIn actionWithDuration:3];
id action2 = [FadeOut actionWithDuration:3];
//Logo runs the actions
[logo runAction: [Sequence actions:action0,action1, action2, nil]];
//Schedules the changeScene method to switch scenes to main menu within 6 seconds of loading.
[self schedule: @selector(changeScene) interval:6.0f];
//Creates a label and positions it, Alternative Visuals
label = [Label labelWithString:@"Alternative Visuals" fontName:@"Verdana" fontSize:22];
label.position = ccp(160, 120);
[self addChild:label];
}
return self;
}
//Method called after intro has run its actions, after 6 seconds it switches scenes.
-(void)changeScene
{
[self removeChild:logo cleanup:YES];
[self removeChild:label cleanup:YES];
Main_Menu *mainMenu = [Main_Menu node];
[[Director sharedDirector] replaceScene: mainMenu];
}
-(void)dealloc
{
[[TextureMgr sharedTextureMgr] removeUnusedTextures];
[label release];
[logo release];
[super dealloc];
}
@end
我是否正确发布了所有内容并避免了泄漏?我在仪器中多次运行它,它没有发现泄漏并且使用了大约 2mb 的内存,这是太多还是预期的数量?替换场景时也会调用dealloc方法吗?
问题 2:
我的主菜单是这样设置的
#import "Main_Menu.h"
#import "Sprite.h"
#import "cocos2d.h"
@implementation Main_Menu
@synthesize background, controlLayer;
-(id) init
{
self = [super init];
if(self != nil)
{
//Create the default background for main menu not including directional pad and highlight box
background = [Sprite spriteWithFile:@"Main_Menu_bg.png"];
background.position = ccp(160,240);
[self addChild:background];
//Adds the control later class to the main menu, control layer class displays and controls the directional pad and selector.
ControlLayer *layer = [[ControlLayer alloc] init];
self.controlLayer = layer;
[layer release];
[self addChild: controlLayer];
}
return self;
}
-(void) dealloc
{
[seld removeChild:background cleanup:YES];
[[TextureMgr sharedTextureMgr] removeUnusedTextures];
[background release];
[controlLayer release];
[super dealloc];
}
@end
我又一次做对了一切吗?我添加到此场景的 ControlLayer 层包含用户用于导航菜单的方向键精灵。在 Instruments 中它还确认它们没有内存泄漏,并且它使用了 4.79 mb 的内存。再一次,这是一个合理的数额吗?我很可能会改用 AtlasSprite 和 AtlastSpriteManager 来节省内存。
我是 cocos2d 的新手,所以如果你发现我做错了什么,请指出!我宁愿在早期阶段改掉坏习惯。如果您有任何未来的内存管理技巧,请分享。
【问题讨论】:
标签: iphone objective-c memory-management cocos2d-iphone