Skip to content

Instantly share code, notes, and snippets.

@pvn
Created September 26, 2018 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pvn/d8342514232521a3a03c002debcf775e to your computer and use it in GitHub Desktop.
Save pvn/d8342514232521a3a03c002debcf775e to your computer and use it in GitHub Desktop.
Helper methods for storing data in UserDefaults using PKDataManager class
class PKDataManager {
static let defaults = UserDefaults.standard
// check if 'key' is present in user defaults
static func isKeyPresentInUserDefaults(key: String) -> Bool {
return defaults.object(forKey: key) != nil
}
// store the SETs as string for given 'key' in user defaults
static func set(_ values: Set<String>, forKey key: String) {
let encodedData = NSKeyedArchiver.archivedData(withRootObject: values)
defaults.set(encodedData, forKey: key)
synchronize()
}
// retrieve the SETs values from user defaults
static func get(forKey key: String) -> Set<String>{
if isKeyPresentInUserDefaults(key: key) {
let decoded = defaults.value(forKey: key)
let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded as! Data )
return (decodedTeams as? Set<String>)!
}
else {
print("Key \(key) is not found")
}
return []
}
// clear 'ALL' the values for the given key
static func clearAll(forKey key: String) {
if isKeyPresentInUserDefaults(key: key) {
defaults.removeObject(forKey: key)
synchronize()
}
}
static func synchronize() {
defaults.synchronize()
}
// remove the SETs as string value for given 'key' in user defaults
static func remove(_ value: String, forKey key: String) {
var items = self.get(forKey: key)
items.remove(value)
clearAll(forKey: key)
set(items, forKey: key)
synchronize()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment