Search code examples
iosswiftnsarraynsuserdefaults

Duplicating items already in array


Every time I run the app, and then re-run it, it saves the same items into the NSUserDefaults even if it is already there.

I tried to fix that with contains code, but it hasn't worked.

What am I missing?

    for days in results! {
        let nD = DayClass()
        nD.dayOfTheWeek = days[“D”] as! String
        let defaults = NSUserDefaults.standardUserDefaults()
            if var existingArr = defaults.arrayForKey("D") as? [String] {
                if existingArr.contains(days["D"] as! String) == false {
                    existingArr.append(nd.dayOfTheWeek)
                }
            } else {
                defaults.setObject([nD.dayOfTheWeek], forKey: "D")
            }
        }

Solution

  • Every time I run the app, and then re-run it, it saves the same items into the NSUserDefaults even if it is already there.

    Yes, because that's exactly what your code does:

    defaults.setObject(existingArr, forKey: "D")
    

    But what is existingArr? It's the defaults you've just loaded before:

    if var existingArr = NSUserDefaults.standardUserDefaults().arrayForKey("D") as? [String]
    

    So what happens is that when you enter the .contains branch, you always do the same operation: you save the existing array.

    Contrary to what your comment in the code states, you're not appending anything to any array in that block, you're saving the existing one.