Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a function when an app first loads

Tags:

ios

swift

I'm trying to write a simple to-do list in Swift that will store the list as an array of Strings and then call it back from memory when the app loads.

I've got the following code:

var itemList = [String]()

func loadData() -> [String] {
    var arr = [String]()

    if NSUserDefaults.standardUserDefaults().objectForKey("storedData") != nil {
        arr = NSUserDefaults.standardUserDefaults().objectForKey("storedData")! as! [String]
    }
    else {
        arr = ["Nothing to do..."]
    }

    return arr
}

func saveData(arr: [String]) {
    NSUserDefaults.standardUserDefaults().setObject(arr, forKey: "storedData")
}

Where I'm getting stuck is in where to place the call to loadData(). This is an app that has two view controllers (one for the list, one for an add item setup), so if I place the loadData() call in viewDidLoad() for the main view controller, the array is called back in from memory (and over-written) every time I switch back to the main view controller.

Where is the best place to call this so that it will load once only, upon the app starting up?

like image 515
lordchancellor Avatar asked Mar 15 '23 23:03

lordchancellor


1 Answers

the array is called back in from memory (and over-written) every time I switch back to the main view controller.

No. viewDidLoad only loads once, when the app starts. Only viewWillApprear and viewDidAppear get called everytime the viewcontroller changes.

Also you could make your code a bit more compact by using if let:

  if let storedData = NSUserDefaults.standardUserDefaults().objectForKey("storedData") as! [String]{
     arr = storedData
  }

But if you want to make sure to load this only once, you can put it in your AppDelegate file in your applicationDidFinishWithOptions method.

But you'd have to make a variable in your AppDelegate file which you can access from your viewController.

like image 162
Christian Avatar answered Mar 28 '23 10:03

Christian