5

I have created UserDefaults with suite,

self.moviesWatchedUserDefaults = UserDefaults(suiteName: "com.apple.tv.2020")

And storing the info in the plist like

self.moviesWatchedUserDefaults.set(data, forKey: key).

Now, while retrieving, I wanted to retrieve all keys & values. For which I am using,

var watchedList = self.moviesWatchedUserDefaults?.dictionaryRepresentation()

But the list which is returned not only contains the items which I stored, but also other keys like NSLanguages, AppleKeyboards, AppleKeyboardsExpanded, CarCapabilities, etc.,

How to retrieve all the keys&values (only the ones which I stored) ?

user2431170
  • 151
  • 2
  • 11

1 Answers1

1

If you have a full list of known keys, you can filter the dictionary.

In the following example I have all my known keys in an enum and I can filter the dictionary, keeping only my keys:

enum UserDefaultsKey: String, CaseIterable {
    case foo
    case bar
    case baz
}

let userDefaults = UserDefaults.standard
userDefaults.set(42, forKey: UserDefaultsKey.foo.rawValue)

let onlyMyValues = userDefaults.dictionaryRepresentation().filter { (key, _) -> Bool in
    UserDefaultsKey.allCases.map { $0.rawValue }.contains(key)
}

print(onlyMyValues) // prints ["foo": 42]
Vadim Belyaev
  • 2,456
  • 2
  • 18
  • 23
  • No, these are like Unknown keys that are received from the backend. – user2431170 Sep 15 '20 at 14:15
  • In this case I'd suggest two options: 1. Track the keys you use to save into UserDefaults and store them for later retrieving. 2. Adopt a more suitable storage, like a custom plist file or a database. CoreData might be a good choice. – Vadim Belyaev Sep 16 '20 at 06:12