[ad_1]
I am creating an app that has a procuring listing and a to-do listing on 2 totally different desk view controllers. I am new to caching and I am probably not proud of how the mannequin I’ve created seems to be. Additionally, it appears to save lots of the information for the procuring listing and never the to-do listing. It saves so effectively that even after deleting an merchandise, it reappears when terminating and reopening the app. The procuring listing shows 2 labels and a favorite button. The to-do listing is only one label. Does anybody have any recommendation?
Right here is the code within the cache mannequin I created:
import Basis
// Mannequin used to cache information within the desk view
struct ShopItemCache {
static let shopItemKey = "store.merchandise.key"
static let toDoKey = "todo.merchandise.key"
static func setItems(objects: [ShopItem]) {
let listing = ShopItems(objects: objects)
if let information = attempt? JSONEncoder().encode(listing),
let json = String(information: information, encoding: .utf8) {
print("json (json)")
UserDefaults.normal.set(json, forKey: shopItemKey)
UserDefaults.normal.synchronize()
}
}
static func setToDoItems(toDoItems: [ToDoItem]) {
let listing = ToDoItems(toDoItems: toDoItems)
if let information = attempt? JSONEncoder().encode(listing),
let json = String(information: information, encoding: .utf8) {
print("json (json)")
UserDefaults.normal.set(json, forKey: toDoKey)
UserDefaults.normal.synchronize()
}
}
static func removeItem(idx: Int) {
var objects = getItems()
objects.take away(at: idx)
UserDefaults.normal.set(objects, forKey: shopItemKey)
UserDefaults.normal.synchronize()
}
static func getItems() -> [ShopItem] {
guard let json = UserDefaults.normal.string(forKey: shopItemKey) else {
print("json is lacking")
return []
}
guard let information = json.information(utilizing: .utf8) else {
print("information is lacking")
return []
}
if let listing = attempt? JSONDecoder().decode(ShopItems.self, from: information) {
return listing.objects
} else {
return []
}
}
static func removeToDoItem(idx: Int) {
var objects = getToDoItems()
objects.take away(at: idx)
UserDefaults.normal.set(objects, forKey: toDoKey)
UserDefaults.normal.synchronize()
}
static func getToDoItems() -> [ToDoItem] {
guard let json = UserDefaults.normal.string(forKey: shopItemKey) else {
print("To-Do json is lacking")
return []
}
guard let information = json.information(utilizing: .utf8) else {
print("information is lacking")
return []
}
if let listing = attempt? JSONDecoder().decode(ToDoItems.self, from: information) {
return listing.toDoItems
} else {
return []
}
}
}
[ad_2]
