Skip to content

Instantly share code, notes, and snippets.

@novalagung
Created October 22, 2017 12:15
Show Gist options
  • Save novalagung/6e61e6eac35e328720997202068def91 to your computer and use it in GitHub Desktop.
Save novalagung/6e61e6eac35e328720997202068def91 to your computer and use it in GitHub Desktop.
UserDefaults wrapper to easily store object or array of object in Swift
import Foundation
class Draw: NSObject, NSCoding {
var id: String = ""
var name: String = ""
var at: Date = Date()
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
id = aDecoder.decodeObject(forKey: "id") as? String ?? ""
name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
at = aDecoder.decodeObject(forKey: "at") as? Date ?? Date()
}
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(name, forKey: "name")
aCoder.encode(at, forKey: "at")
}
}
// get all data
let data = LocalStorage.getAll()
// get data by id
let row = LocalStorage.get("0001")
// save data
let row = Draw()
LocalStorage.save(row)
class LocalStorage {
private static var key = "data"
static func getAll() -> [Draw] {
let storage = UserDefaults.standard
if let rawValue = storage.value(forKey: self.key) as? Data {
if let data = NSKeyedUnarchiver.unarchiveObject(with: rawValue) as? [Draw] {
return data
}
}
return [Draw]()
}
static func get(_ id: String) -> Draw {
let rows = getAll().filter { (draw) -> Bool in
return draw.id == id
}
return rows.first ?? Draw()
}
static func save(_ draw: Draw) {
var all = getAll()
all.append(draw)
let rawValue = NSKeyedArchiver.archivedData(withRootObject: all)
let storage = UserDefaults.standard
storage.set(rawValue, forKey: self.key)
storage.synchronize()
}
static func saveAll(_ all: [Draw]) {
let rawValue = NSKeyedArchiver.archivedData(withRootObject: all)
let storage = UserDefaults.standard
storage.set(rawValue, forKey: self.key)
storage.synchronize()
}
static func delete(_ id: String) {
let all = getAll().filter { (each) -> Bool in
return each.id != id
}
self.saveAll(all)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment