Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a code for only once?

I'm working on an iPhone app, and I'm wondering if I could run some code segment for only once (in other words: an initialization code, that I want it to be executed only at the very first run). Here's my code, that I execute it at didFinishLaunchingwithOptions method:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

// Override point for customization after application launch.

// Add the tab bar controller's view to the window and display.
[self.window addSubview:tabBarController.view];
[self.tabBarController setSelectedIndex:2];
[self.window makeKeyAndVisible];

[self createPlist1];
[self createPlist2];
[self createPlist3];

return YES;

}

I want the last three messages to be executed only at the very first run. I thought I could use the UserDefaults and set a key after these messages executes (at the first run) and check for the value of that key at each run, but I'm feeling that there's a better idea -which I don't know.

Thanks in advance.

like image 871
ObjProg Avatar asked Nov 30 '22 08:11

ObjProg


2 Answers

Using a setting (via NSUserDefaults) is how it's normally done. For added benefit, give the setting the meaning of "last run version"; this way, you'll get a chance to run code not only once per app lifetime, but also once per version upgrade.

That said, your run-once code has persistent side effects, right? Those plists go somewhere probably. So you can check if they exist before creating them. Use the result of the run-once code as a trigger for running it again.

EDIT:

NSUserDefaults *Def = [NSUserDefaults standardUserDefaults];
NSString *Ver = [Def stringForKey:@"Version"];
NSString *CurVer = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleVersionKey];
if(Ver == nil || [Ver compare:CurVer] != 0)
{
    if(Ver == nil)
    {
        //Run once per lifetime code
    }
    //Run once-per-upgrade code, if any
    [Def setObject:CurVer forKey:@"Version"];
}
like image 151
Seva Alekseyev Avatar answered Dec 05 '22 01:12

Seva Alekseyev


A much simpler possible solution ->

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"FirstTimeBool"]==nil)
{
    [defaults setObject:@"YES" forKey:@"FirstTimeBool"];
    ... //Code to be executed only once until user deletes the app!
    ...
like image 45
Deepak Thakur Avatar answered Dec 05 '22 01:12

Deepak Thakur