我正在为iPhone制作一款由4款迷你游戏组成的游戏。每个迷你游戏都是一个独立的xib。每个游戏都有自己的菜单和游戏关卡。进入主菜单,选择要加载的游戏。
这就是我目前加载每个xib的方式。
MainGameViewController.h
@interface MainGameViewController : UIViewController {
UIViewController *currentView;
int currentViewId;
}
@property (nonatomic, retain) UIViewController *currentView;
- (void)displayView:(int)intNewView;
@end
MainGameViewController.m
@implementation MainGameViewController
@synthesize currentView;
- (void)viewDidLoad {
[super viewDidLoad];
currentView = [[LogoScreen alloc] init];
[self.view addSubview:currentView.view];
}
- (void)displayView :(int)intNewView
{
currentViewId = intNewView;
currentView = nil;
[currentView release];
switch (intNewView) {
case SCR_GAME1:
currentView = [[Game1View alloc] init];
break;
case SCR_GAME1LEVEL:
currentView = [[Game1LevelView alloc] init];
break;
case SCR_GAME2:
currentView = [[Game2View alloc] init];
break;
case SCR_GAME2LEVEL:
currentView = [[Game2LevelView alloc] init];
break;
case SCR_GAME3:
currentView = [[Game3View alloc] init];
break;
case SCR_GAME3LEVEL:
currentView = [[Game3LevelView alloc] init];
break;
case SCR_GAME4:
currentView = [[Game4View alloc] init];
break;
case SCR_GAME4LEVEL:
currentView = [[Game4LevelView alloc] init];
break;
default:
currentView = [[MainView alloc] init];
break;
}
[self.view addSubview:currentView.view];
}
- (void)dealloc {
[currentView release];
currentView = nil;
[super dealloc];
}
@end
这就是关卡的启动方式。Game1View.m
@implementation Game1View
-init {
if (self == [super init]) {
MainGameAppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
isSoundOn = (appdelegate.gvar.soundstate == 1);
gamestate = GAME_STATUS_START;
}
return self;
}
...
...
- (void)launchgame {
MainGameAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
appDelegate.gvar.currentId = objectid;
[appDelegate displayView:SCR_GAME1LEVEL_GAME];
}
- (void)returnToMain {
MainGameAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate displayView:SCR_MAIN];
}
@end
MainGameAppDelegate.m
@implementation MainGameAppDelegate
@synthesize window;
@synthesize viewController;
- (void) displayView:(int)intNewView {
[viewController displayView:intNewView];
}
@end
目前,当我不断在视图之间切换,然后应用程序崩溃时,我会收到内存警告。我的问题是,这是加载这些视图的正确方式吗?我已经发布了我在游戏寿命内分配的所有内容,现在我对占用内存的内容感到不知所措。任何帮助都将不胜感激。
您没有正确地发布游戏视图,因为您的代码在调用release之前实际上会将currentView设置为nil,这意味着您将泄露创建的每个游戏视图。
- (void)displayView :(int)intNewView
{
currentViewId = intNewView;
currentView = nil;
[currentView release];
switch (intNewView) {
你可能想这样做:
- (void)displayView :(int)intNewView
{
currentViewId = intNewView;
[currentView release];
currentView = nil;
switch (intNewView) {
此外,将视图控制器命名为"视图"会让人感到困惑。考虑给它们更多描述性的名称,比如xxxController。
编辑1:
您还需要确保旧游戏在发布之前已从视图层次结构中删除。在发布视图之前先调用[currentView.view removeFromSuperview]将其删除。