我正在开发一款游戏,因为我想要不断添加点数,为此我使用了plist,但每当屏幕消失并开始时,plist就会重新开始。该怎么办?
提前感谢。
要在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和/或intValue来操作它。checkfirstrn 是必需的,因为您的用户的设备在应用程序第一次运行时不包含默认的plist和初始值,您必须创建一个初始集。
你可以创建AppDelegate变量并将其存储在其中。该作用域在整个应用程序中保留,直到应用程序关闭。
在AppDelegate.h例如
NSString *string;
@property(nonatomic, strong) NSString *string;
在AppDelegate.m @synthesize string;
string = @"";
然后是你的类add #import "AppDelegate.h"
然后在你的代码中((AppDelegate *)[UIApplication SharedApplication].Delegate).string = @"1";