0

EDIT:

I tried to set up NSUserDefaults last night but an error keeps occurring:

ViewController3:

save data

 @IBAction func addButtonTapped(sender: UIButton) {
    var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()

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

    var dataSet:NSMutableDictionary = NSMutableDictionary()
    dataSet.setObject(textField.text, forKey: "exercises")

    if ((itemList) != nil){ 
        var newMutableList:NSMutableArray = NSMutableArray();

        for dict:AnyObject in itemList!{
            newMutableList.addObject(dict as NSDictionary)
        }

        userDefaults.removeObjectForKey("exercisesList")
        newMutableList.addObject(dataSet)
        userDefaults.setObject(newMutableList, forKey: "exercisesList")

    }else{ 
        userDefaults.removeObjectForKey("exercisesList")
        itemList = NSMutableArray()
        itemList!.addObject(dataSet)
        userDefaults.setObject(itemList, forKey: "exercisesList")
    }

    userDefaults.synchronize()

    self.view.endEditing(true)
    textField.text = ""

}

ViewController1:

load data

 var exercises:NSMutableArray = NSMutableArray();


override func viewDidAppear(animated: Bool) {
    var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()

    var itemListFromUserDefaults:NSMutableArray? = userDefaults.objectForKey("itemList") as? NSMutableArray

    if ((itemListFromUserDefaults) != nil){
        exercises = itemListFromUserDefaults!
    }
}

Now I wanted to use the loaded data for UIPickerView

 func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
    switch pickerView {
    case pickerView1:
        return exercises[row] as String
    case pickerView2:
        return reps[component][row]
    case pickerView3:
        return weight[component][row]
    default:
        assertionFailure("Unknown pickerView")
    }
}

But at the point where the UIPickerView should return the exercises it is empty. Need some help here.

santa1
  • 17
  • 8
  • "How to store the added exercises" - store for how long? For later in the same run of the app? For later even after the app has been terminated? I mean, `var exercises` _is_ storage, so in what sense is the problem not already solved? – matt Jan 22 '15 at 20:22
  • NSArray has a writeToFile() method ... – Martin R Jan 22 '15 at 20:24
  • ... have a look at http://stackoverflow.com/questions/24246749/whats-the-equivalent-of-nsarrays-writetofile-atomically-in-swift-and-array. – Martin R Jan 22 '15 at 20:29
  • @matt : take a look at my edit please. information should be stored in the app after closing the app until the user removes it. – santa1 Jan 22 '15 at 20:32
  • Write a JSON string to file. – Ian MacDonald Jan 22 '15 at 20:45

3 Answers3

0

Don't use NSUserDefaults to pass variables.

Add a public property (in the .h file) to destinationViewController and set that property with the value (the array) in prepareForSegue.

To save the array between app launches do as @Martin suggests, writing the array to the Documents directory.There are many answers here with that information.

zaph
  • 111,848
  • 21
  • 189
  • 228
0

How to store your arrays using NSUserDefaults is pretty simple and I encourage you to try it.

var exercises = ["A","B","C"]
NSUserDefaults.standardUserDefaults().setObject(exercises, forKey: "exercises")

How to load your string arrays using NSUserDefaults

if let myLoadedStringArray = NSUserDefaults.standardUserDefaults().stringArrayForKey("exercises"){
    println(myLoadedStringArray)   // "[A, B, C]"
}
// Note: myLoadedStringArray has no value outside curly brackets

How to delete/reset a value stored using NSUserDefaults

NSUserDefaults.standardUserDefaults().removeObjectForKey("exercises")

println(NSUserDefaults.standardUserDefaults().stringArrayForKey("exercises"))    // "nil"

If you prefer to store it as a file at the documents folder you can do as follow

let fileUrl = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL).URLByAppendingPathComponent("exercises.db")
(exercises as NSArray).writeToURL(fileUrl, atomically: true)  // true
// forced unwrap if you are sure it won't return nil
let loadedArray = NSArray(contentsOfURL: fileUrl)! as [String]
// or use if let to safely unwrap your array
if let loadedArray = NSArray(contentsOfURL: fileUrl) as? [String] {
    println(loadedArray)  // "[A, B, C]"
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • I tried as you suggested but I'm not quite sure if its working because an error keeps occurring. Please take a look at my edited question. Thank you! – santa1 Jan 24 '15 at 10:18
0

I think I've got this.

In your code, you read exercises from UserDefaults in viewDidAppear, which will be called after func pickerView(...) -> String! is called. That's why in func pickerView(...) -> String! the exercises is always empty.

To do this correctly, you need to initialize exercises in init() or viewDidLoad()

ljk321
  • 16,242
  • 7
  • 48
  • 60
  • So what other options do I have? I know I could write viewDidLoad (if that would change anything) but this would mean, that the data will only be loaded once. – santa1 Jan 25 '15 at 10:31
  • @santa1 You could also write it within `func pickerView()->String`. It will be "slower", but surely acceptable. With more optimization(caching or something), the performance shouldn't be a problem. – ljk321 Jan 25 '15 at 10:35
  • And whats about reloading the data of the picker view within the func of the NSUserDefault? Would that be possible? – santa1 Jan 25 '15 at 10:40
  • EDIT: I have tried as you suggested but something else seems to be wrong. Just can't figure out what. – santa1 Jan 25 '15 at 10:52
  • @santa1 I'm guessing there are more than one picker view, and they need to change dynamiclly. If something can trigger the change, would it be ok to just use `pickerView.reloadAllComponents` ? – ljk321 Jan 25 '15 at 11:06
  • Yes there are more but only one should use the date from NSUserDefaults. I'll try. – santa1 Jan 25 '15 at 17:35