From 795146cde4a3528c4f8e8a43d42d9d8ee398dd47 Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Tue, 20 Dec 2022 15:13:18 -0500 Subject: [PATCH] Cache lists in CoreData --- Tusker/API/MastodonController.swift | 11 +++++ Tusker/CoreData/ListMO.swift | 41 +++++++++++++++++++ .../Tusker.xcdatamodel/contents | 10 +++++ 3 files changed, 62 insertions(+) create mode 100644 Tusker/CoreData/ListMO.swift diff --git a/Tusker/API/MastodonController.swift b/Tusker/API/MastodonController.swift index 4e4b10d7..32e7419b 100644 --- a/Tusker/API/MastodonController.swift +++ b/Tusker/API/MastodonController.swift @@ -317,6 +317,17 @@ class MastodonController: ObservableObject { DispatchQueue.main.async { self.lists = lists.sorted(using: SemiCaseSensitiveComparator.keyPath(\.title)) } + let context = self.persistentContainer.backgroundContext + context.perform { + for list in lists { + if let existing = try? context.fetch(ListMO.fetchRequest(id: list.id)).first { + existing.updateFrom(apiList: list) + } else { + _ = ListMO(apiList: list, context: context) + } + } + self.persistentContainer.save(context: context) + } } } } diff --git a/Tusker/CoreData/ListMO.swift b/Tusker/CoreData/ListMO.swift new file mode 100644 index 00000000..4b1b5436 --- /dev/null +++ b/Tusker/CoreData/ListMO.swift @@ -0,0 +1,41 @@ +// +// ListMO.swift +// Tusker +// +// Created by Shadowfacts on 12/20/22. +// Copyright © 2022 Shadowfacts. All rights reserved. +// + +import Foundation +import CoreData +import Pachyderm + +@objc(ListMO) +public final class ListMO: NSManagedObject { + + @nonobjc public class func fetchRequest() -> NSFetchRequest { + return NSFetchRequest(entityName: "List") + } + + @nonobjc public class func fetchRequest(id: String) -> NSFetchRequest { + let req = NSFetchRequest(entityName: "List") + req.predicate = NSPredicate(format: "id = %@", id) + return req + } + + @NSManaged public var id: String + @NSManaged public var title: String + +} + +extension ListMO { + convenience init(apiList list: List, context: NSManagedObjectContext) { + self.init(context: context) + self.updateFrom(apiList: list) + } + + func updateFrom(apiList list: List) { + self.id = list.id + self.title = list.title + } +} diff --git a/Tusker/CoreData/Tusker.xcdatamodeld/Tusker.xcdatamodel/contents b/Tusker/CoreData/Tusker.xcdatamodeld/Tusker.xcdatamodel/contents index 46d02c58..f6ff2009 100644 --- a/Tusker/CoreData/Tusker.xcdatamodeld/Tusker.xcdatamodel/contents +++ b/Tusker/CoreData/Tusker.xcdatamodeld/Tusker.xcdatamodel/contents @@ -46,6 +46,15 @@ + + + + + + + + + @@ -121,5 +130,6 @@ + \ No newline at end of file