Storing results after screen is disappear

后端 未结 2 1767
后悔当初
后悔当初 2020-12-12 07:50

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

相关标签:
2条回答
  • 2020-12-12 08:06

    You can make AppDelegate variables and store it in them. There scope remains in the complete application until the application closes.

    In AppDelegate.h for example

    NSString *string;
    
    @property(nonatomic, strong) NSString *string;
    

    In AppDelegate.m

    @synthesize string;
    

    in applicationDidFinishLaunchingWithOptions

    string = @"";
    

    And then is your classes add #import "AppDelegate.h"

    then in your code ((AppDelegate *)[UIApplication SharedApplication].Delegate).string = @"1";

    0 讨论(0)
  • 2020-12-12 08:10

    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.

    0 讨论(0)
提交回复
热议问题