Jake Walker
Jake Walker

Reputation: 305

How to run data only once in whole app's life?

I want to set some data into NSUserdefaults, but I only want it to be set at the start. I have a feeling this would go somewhere into AppDelegate.

For example, I want to put a "isLoggedIn" bool check, but I need to set it equal false before runtime, so that it can check it at runtime.

Upvotes: 0

Views: 59

Answers (1)

Duncan C
Duncan C

Reputation: 131436

NSUserDefaults (or UserDefaults in Swift 3) has a function register(defaults:) that lets you provide a dictionary containing "default defaults" or starting defaults. That's what you need. I usually put a call to register(defaults:) in the App delegate's initialize method so it's called very early in the app startup, before any of your instance methods get called. The initialize method in your app delegate might look like this in Swift:

func initialize() {
  let dict: [String: Any] = [
    "Key1": "value1",
    "Key2": 3,
    "isLoggedIn": false]
  UserDefaults.standard.register(defaults: dict)
}

Upvotes: 3

Related Questions