Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

iphone - Storing results after screen is disappear

I am developing a game,in that i want to add the points continuously,for this i used plist but whenever the screen is disappear and starts then plist starts again.what to do?

Thanks in Advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To add more info to Ahmed's answer you should implement in your AppDelegate.m three methods like this:

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];      
    }
// ...

Later in your application, after importing AppDelegate.h you can use the UIAppDelegate.gamescore to access the AppDelegate's property.

And you have to remember that gamescore is an NSNumber object, you have to manipulate it using NSNumber's numberWithInt and/or intValue.

The CheckFirstRun is needed because your user's device at application first run doesn't contain the default plist and the initial values, you have to create an initial set.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...