0

我正在开发一个游戏,因为我想连续添加积分,为此我使用了 plist,但是每当屏幕消失并启动时,plist 就会再次启动。该怎么办?

提前致谢。

4

2 回答 2

3

要向 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对象,你必须使用NSNumbernumberWithInt和/或intValue来操作它。

CheckFirstRun是必需的,因为您的用户设备在应用程序首次运行时不包含默认 plist 和初始值,您必须创建一个初始集。

于 2013-05-10T05:53:56.413 回答
0

您可以制作 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";

于 2013-05-10T04:51:56.737 回答