Yotam
Yotam

Reputation: 10495

Swift: can't save array to UserDefaults

I have a class called Stop. This class implements NSCoding. I can save instances of Stop to UserDefaults with no problems. So far, so good. My problem is with saving an Array of stops. This is what I try:

private func save(stopArray array: [Stop],withKey key: String) {
        let data = NSKeyedArchiver.archivedData(withRootObject: array)
        self.userDefaults.set(data, forKey: key)
        self.userDefaults.synchronize()
    }

private func loadStopArray(key: String) -> [Stop]? {
        guard let data = self.userDefaults.object(forKey: key) as? Data else {
            return nil
        }
        return NSKeyedUnarchiver.unarchiveObject(with: data) as? [Stop]
}

Now, every time I call loadStopArray I get an empty array. Not nil, just an empty array.

Any ideas? Thanks!

Upvotes: 0

Views: 406

Answers (1)

Emptyless
Emptyless

Reputation: 3051

You are confusing loading Object and Data. self.userDefaults.object() to self.userDefaults.data() wil yield the data.

private func loadStopArray(key: String) -> [Stop]? {
        if let data = self.userDefaults.data(forKey: key) {
            return NSKeyedUnarchiver.unarchiveObject(with: data) as? [Stop]
        } else {
            return nil
        }
}

Upvotes: 2

Related Questions