【发布时间】:2013-05-10 04:43:50
【问题描述】:
我正在开发一个游戏,因为我想连续添加积分,为此我使用了 plist,但每当屏幕消失并启动时,plist 就会再次启动。该怎么办?
提前致谢。
【问题讨论】:
-
需要在-(void)viewWillDisappear中编写保存游戏数据的代码;
标签: iphone
我正在开发一个游戏,因为我想连续添加积分,为此我使用了 plist,但每当屏幕消失并启动时,plist 就会再次启动。该怎么办?
提前致谢。
【问题讨论】:
标签: iphone
要向 Ahmed 的答案添加更多信息,您应该在 AppDelegate.m 中实现如下三个方法:
AppDelegate.h
NSNumber *gamescore;
@property(nonatomic, strong) NSNumber *gamescore;
#define UIAppDelegate \
((AppDelegate *)[UIApplication sharedApplication].delegate)
AppDelegate.m
@synthesize gamescore;
- (BOOL) checkFirstRun {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSNumber *defaultcheck;
defaultcheck = [defaults objectForKey:@"GameScore"];
if (defaultcheck==nil) {
return TRUE;
} else {
return FALSE;
}
}
- (void) storeGlobalVars {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:gamescore forKey:@"GameScore"];
[defaults synchronize];
}
- (void) readGlobalVars {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
gamescore = [defaults objectForKey:@"GameScore"];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
// ...
if ([self checkFirstRun]) {
// first run, lets create basic default values
gamescore = [NSNumber numberWithInt:0];
[self storeGlobalVars];
} else {
[self readGlobalVars];
}
// ...
稍后在您的应用程序中,导入 AppDelegate.h 后,您可以使用 UIAppDelegate.gamescore 访问 AppDelegate 的属性。
而且你必须记住,gamescore 是一个 NSNumber 对象,你必须使用 NSNumber 的 numberWithInt 和/或 NSNumber 来操作它em>intValue.
CheckFirstRun 是必需的,因为您的用户设备在应用程序首次运行时不包含默认 plist 和初始值,您必须创建一个初始集。
【讨论】:
您可以制作 AppDelegate 变量并将其存储在其中。在应用程序关闭之前,完整的应用程序仍然存在范围。
在 AppDelegate.h 中 例如
NSString *string;
@property(nonatomic, strong) NSString *string;
在 AppDelegate.m 中
@synthesize string;
在 applicationDidFinishLaunchingWithOptions 中
string = @"";
然后是你的课
添加#import "AppDelegate.h"
然后在您的代码中
((AppDelegate *)[UIApplication SharedApplication].Delegate).string = @"1";
【讨论】: