我正在制作一款包含4款迷你游戏的iPhone游戏。每个迷你游戏都是独立的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
当我在视图之间切换然后应用程序崩溃时,我正在收到内存警告。 我的问题是,这是加载这些视图的正确方法吗?我已经发布了我在游戏生命周期中分配的所有内容,而现在我正在为记忆带来的东西感到茫然。任何帮助将不胜感激。
答案 0 :(得分:3)
您没有正确发布游戏视图,因为您的代码在调用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]以首先删除它。