0

I made a to do list app and I got an array called toDo & a textView in each cell. I want the array to be saved in the NSUserDefaults, but whenever I quit the app and open it again - it doesn't save it.

Here is what I tried:

let def = NSUserDefaults.standardUserDefaults()
var key = "keySave"

        override func viewDidLoad() {
             super.viewDidLoad()
             def.setObject(toDo, forKey: "keySave")
        }
        func textViewDidEndEditing(textView: UITextView) {
            todoTableView.reloadData()
            def.setObject(toDo, forKey: "keySave")
        }
Eliko
  • 1,137
  • 4
  • 16
  • 26
  • What is `def` in your code? And, for the `NSUserDefaults` objects, you have to call `synchronize` method after inserting objects, if you want your data saved. – Fahri Azimov Sep 23 '15 at 11:52
  • sorry, I edited it - def is `NSUserDefaults.standardUserDefaults()`. And in iOS 8 you don't need to save it by `synchronize`. – Eliko Sep 23 '15 at 11:56
  • what kind of objects stores `toDo` array? they're just Strings? – lucaslt89 Sep 23 '15 at 11:57
  • What are the objects in the array? – Fogmeister Sep 23 '15 at 11:57
  • 1
    @FahriAzimov More specifically, `synchronize` writes the data to disk immediately. You don't need to call it in most cases. – Caleb Sep 23 '15 at 11:58
  • @lucaslt89, Fogmeister - The `toDo` array is just Strings. – Eliko Sep 23 '15 at 11:58
  • Yeah, sorry, missed the word "immediately". – Fahri Azimov Sep 23 '15 at 12:01
  • 4
    Here you go... Swift Strings are not compatible with NSUserDefaults. You have to cast them to NSString. http://stackoverflow.com/questions/25420651/store-string-in-nsuserdefaults-swift Going to close as a duplicate question. – Fogmeister Sep 23 '15 at 12:01
  • The lesson i do not use `NSUserDefaults` as a data model. Create a class with `NSCoding` support and archive to a file. Consider the name: NS**UserDefaults**, that does not sound like a data model. – zaph Sep 23 '15 at 12:05
  • @zaph I agree that one should use `NSUserDefaults` appropriately, but that's really not the cause of the problem here. – Caleb Sep 23 '15 at 12:11
  • @Fogmeister I don't understand how the answer in the link is helping me.. Can you explain please? – Eliko Sep 23 '15 at 12:16
  • Notice that was a comment, not an answer. @Fogmeister provided a solution. However, using a real data model would solve the problem and using `NSUserDefaults` is the cause of the problem. – zaph Sep 23 '15 at 12:17
  • @zaph Can you give an example of that? – Eliko Sep 23 '15 at 12:18

0 Answers0