-3

In ViewController3 the user can save some text via button click to the NSUserDefaults (to use it elsewhere). In the same ViewController there is also a tableView (used to delete specific items from NSUserDefaults)

So I have to load the data back with:

override func viewDidLoad() {
    super.viewDidLoad()

    var exercisescopy = NSMutableArray(array: exercises)

    var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()

    var exercisesListFromUserDefaults:NSMutableArray? = userDefaults.objectForKey("exercisesList") as? NSMutableArray

    if ((exercisesListFromUserDefaults) != nil){
        exercises = exercisesListFromUserDefaults!
    }
    self.tableView.reloadData()

}

so that the data is there when you get to the third ViewController but how to get the data right back after saving a new element to NSUserDefaults? So that it is displayed in the tableView right now?

Wain
  • 118,658
  • 15
  • 128
  • 151
santa1
  • 17
  • 8

2 Answers2

0

You can use NSNotificationCenter to observe changes in NSUserDefaults.

This answer describes it well.

For swift it is:

NSNotificationCenter.defaultCenter().addObserver(self, "reloadMyData:", NSUserDefaultsDidChangeNotification, nil)

Where reloadMyData: is your function to trigger table reloading.

Don't forget to strip the observer in deinit as in:

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}
Community
  • 1
  • 1
Warren Burton
  • 17,451
  • 3
  • 53
  • 73
0

You really don't wanna do this, Using the NSUserDefault for passing Data. NSNotification center is cool about that as @Burton suggested. If your data is really big you can use CoreData. If you really wanna do this that you intend here is how ...

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];  
NSString *firstName = [defaults objectForKey:@"firstName"];
NSString *lastName = [defaults objectForKey:@"lastname"];

Here assummed that firstname & lastname were saved preiviously.

Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44