SAP DEV
SAP DEV

Reputation: 111

iOS: NSUserDefaults during the first-run-application?

I am using the NSUserDefaults Class to store some data but I have a normal conflict concerning the initialization.

I mean:

In my Class A in the didViewLoad method, I have set my NSUserDefaults data and afterwards in my Class B, in the didViewLoad, I want to get my NSUserDefaults data.

I have seen with the breakpoints that during the first-run-application, all the didViewLoad() of the application are performed, so I would like to put a condition in the viewDidLoad() of my Class B for the first-run-application to avoid random data initialization.

Have we got a keyword in Objective-C's framework instead of using static variable ?

eg:

ClassA--> didViewLoad():

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:kdataText forKey:@"udVariable"];

ClassB-> didViewLoad():

And:

ClassB--> didViewLoad():

if (!first_run){ // first_run --> KEYWORD FRAMEWORK???
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *var = [defaults objectForKey:@"udVariable"];
}

Upvotes: 1

Views: 732

Answers (3)

aequinox
aequinox

Reputation: 135

Swift 4:

Add this code to AppDelegate within didFinishLaunchingWithOptions:

UserDefaults.standard.register(defaults: ["cardMatrixRows": NSNumber(value: 4), "cardMatrixColumns": NSNumber(value: 3)])

Upvotes: 1

matt
matt

Reputation: 534895

The key is to call registerDefaults even earlier, like in main or in the app delegate's applicationDidFinishLaunching:. From an app of mine:

[[NSUserDefaults standardUserDefaults] registerDefaults:
    @{@"cardMatrixRows":@4, @"cardMatrixColumns":@3}];

Now there is a default default, as it were, and the order of events / view controllers no longer matters.

Upvotes: 4

AndrewShmig
AndrewShmig

Reputation: 4923

Just check if [defaults objectForKey:@"udVariable"] != nil

You can also use macro #define.

Upvotes: 0

Related Questions