Created
September 26, 2018 21:01
-
-
Save pvn/d8342514232521a3a03c002debcf775e to your computer and use it in GitHub Desktop.
Helper methods for storing data in UserDefaults using PKDataManager class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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