Question

I need a way to initialize a lot of objects only the 1st time my app is installed. So I thought I use this:

    -(id) init {
    self = [super init];

       if(self) {
         NSUserDefaults *myUD = [NSUserDefaults standardUserDefaults];
         [myUD  setObject:@"5" forKey:@"Extra"]; // 5 giving 4 extra diaries
         [myUD  setObject:@"0" forKey:@"CatchingUp"]; // it's a live diary
         [myUD  setObject:@"888" forKey:@"SendingSuccess"];
         [myUD  synchronize];
       }
    return self;
    }

I obviously have many more than theses to initialize but it's just to give you the idea of what I did.

I deleted the app from my phone in order to test, but the init wasn't performed. I put it before ViewDidLoad.

What am I doing wrong please or is there a better way to do it ?

Thank you very much in advance.

Was it helpful?

Solution

If you just want to set up some values at the first time your app runs,

Put this code in app delegate and use this method in didFinishLaunchingWithOptions method, or you can put this code in your view controller and use this method in viewDidLoad method:)

- (void)setDefaultInfoValue {
      if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];
        //put you code here
        NSUserDefaults *myUD = [NSUserDefaults standardUserDefaults];
        [myUD  setObject:@"5" forKey:@"Extra"]; // 5 giving 4 extra diaries
        [myUD  setObject:@"0" forKey:@"CatchingUp"]; // it's a live diary
        [myUD  setObject:@"888" forKey:@"SendingSuccess"];
        [myUD  synchronize];
      }
    }

OTHER TIPS

At the moment you code will run whenever you create an instance of the class that contains the code - this is likely not what you want (and isn't what you describe).

Instead of setObject:forKey:, you should use registerDefaults: which installs the specified values only if values don't already exist and doesn't save the values to disk. This could be done in the app delegate, or separately in each class that uses different keys from user defaults.

The immediate problem you observe is probably that you aren't creating an instance of the class which contains your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top