1

Im trying to set an array of objects to user defaults but is not appending.

declaring the var for the array in my AllFormulas Class:

let defaults = UserDefaults.standard    
static var lineOne1 = UserDefaults.standard.array(forKey: "line1") as? [Formulas] ?? []
init() {
//formula names and values 

then im starting with an empty array

lineOne1 = []
}

appending to the array in my AddViewController Class :

 func lineOneAdd() {
    let line1 = lineOne1
    lineOne1.append(formulaAppend)
    defaults.set(line1, forKey: "line1")
    defaults.synchronize()

}

then calling the userDefaults in view did load in MainViewController Class:

line1[indexPath.row] // as my cellForRowAt in tableView


print(line1)
//which prints : []

any idea what im doing wrong? thanks in advance

Mark Rogers
  • 95
  • 1
  • 7

1 Answers1

1

You seem to be appending to the wrong array:

lineOne1.append(formulaAppend)

Should be:

line1.append(formulaAppend)
jake
  • 1,226
  • 8
  • 14
  • I tried that. but this is what happens when i call that function "*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object ( "MyProject.Formulas" ) for key line1' – Mark Rogers Jun 05 '19 at 03:41
  • @MarkRogers does your `Formula` class implement (subclass) `Codable`? Also rmaddy is correct, you should be modifying the global. – jake Jun 05 '19 at 03:57
  • No, Formula does not have a subclass. I have another file AllFormulas class which then I use init() to declare each formulas values... Its in that class I am also declaring my arrays for lineOne1. Then in a AddViewController I select the formula I would like to append and view on my MainViewController in a tableView. – Mark Rogers Jun 05 '19 at 04:03
  • If you need to store an object in UserDefaults, I think conforming to `Codable` is best practice. See [this link](https://stackoverflow.com/questions/44876420/save-struct-to-userdefaults). Please note though you typically should use CoreData to store objects as opposed to UserDefaults, which is more often used for preferences. – jake Jun 05 '19 at 04:14
  • I did go the route of CoreData first but was having issues with formula I have showing in the tableview. I starting thinking UserDefaults might be an easier approach to the solution – Mark Rogers Jun 05 '19 at 04:18