0

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.

username0013
  • 79
  • 1
  • 8

2 Answers2

3

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.

nzs
  • 3,252
  • 17
  • 22
  • but where i have to use the plist here – username0013 May 10 '13 at 06:39
  • NSUserDefaults implicitly means a plist stored in your application bundle. You dont have to care, the framework will care how to access plist file – nzs May 10 '13 at 06:41
  • Please see to SO answer how to see this plist file: http://stackoverflow.com/questions/1676938/easy-way-to-see-saved-nsuserdefaults – nzs May 10 '13 at 06:42
0

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";

Ahmed Z.
  • 2,329
  • 23
  • 52