0

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!

3
  • 1
    In order to judge what's happening, I think we'd need to see your implementation of Stop. Commented Jan 8, 2017 at 15:29
  • Are you sure that you are using the same exact key when saving and retrieving? Commented Jan 8, 2017 at 15:32
  • @matt you were right, my NSCoder constructor was returning nil... Thanks! Commented Jan 9, 2017 at 7:39

1 Answer 1

2

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
        }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.