init commit - bring project over from Mood
This commit is contained in:
@@ -2,20 +2,71 @@
|
||||
// Persistence.swift
|
||||
// Shared
|
||||
//
|
||||
// Created by Trey Tartt on 1/10/22.
|
||||
// Created by Trey Tartt on 1/5/22.
|
||||
//
|
||||
|
||||
import CoreData
|
||||
|
||||
struct PersistenceController {
|
||||
static let shared = PersistenceController()
|
||||
static let shared = PersistenceController.persistenceController
|
||||
|
||||
private static var persistenceController: PersistenceController {
|
||||
#if targetEnvironment(simulator)
|
||||
return PersistenceController(inMemory: false)
|
||||
#else
|
||||
return PersistenceController(inMemory: false)
|
||||
#endif
|
||||
|
||||
static var preview: PersistenceController = {
|
||||
let result = PersistenceController(inMemory: true)
|
||||
let viewContext = result.container.viewContext
|
||||
for _ in 0..<10 {
|
||||
let newItem = Item(context: viewContext)
|
||||
}
|
||||
|
||||
public var viewContext: NSManagedObjectContext {
|
||||
return PersistenceController.shared.container.viewContext
|
||||
}
|
||||
|
||||
public func add(mood: Mood, forDate date: Date) {
|
||||
let newItem = MoodEntry(context: viewContext)
|
||||
newItem.timestamp = Date()
|
||||
newItem.moodValue = Int16(mood.rawValue)
|
||||
newItem.date = date
|
||||
|
||||
do {
|
||||
try viewContext.save()
|
||||
} catch {
|
||||
let nsError = error as NSError
|
||||
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
|
||||
}
|
||||
}
|
||||
|
||||
public func moodEntries(forStartDate date: Date, count: Int) -> [MoodEntry] {
|
||||
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
|
||||
|
||||
fetchRequest.fetchLimit = count
|
||||
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
|
||||
|
||||
var calendar = Calendar.current
|
||||
calendar.timeZone = NSTimeZone.local
|
||||
|
||||
let dateFrom = calendar.startOfDay(for: Date())
|
||||
|
||||
// Set predicate as date being today's date
|
||||
let fromPredicate = NSPredicate(format: "date <= %@", dateFrom as NSDate)
|
||||
let datePredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [fromPredicate])
|
||||
fetchRequest.predicate = datePredicate
|
||||
let entries = try! viewContext.fetch(fetchRequest)
|
||||
|
||||
if entries.count >= count {
|
||||
return Array(entries)
|
||||
} else {
|
||||
return entries
|
||||
}
|
||||
}
|
||||
|
||||
func populateTestData() {
|
||||
for idx in 1..<25 {
|
||||
let newItem = MoodEntry(context: viewContext)
|
||||
newItem.timestamp = Date()
|
||||
newItem.moodValue = Int16(Mood.allValues.randomElement()!.rawValue)
|
||||
newItem.date = Calendar.current.date(byAdding: .day, value: -idx, to: Date())
|
||||
}
|
||||
do {
|
||||
try viewContext.save()
|
||||
@@ -25,11 +76,69 @@ struct PersistenceController {
|
||||
let nsError = error as NSError
|
||||
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
|
||||
}
|
||||
return result
|
||||
}()
|
||||
|
||||
}
|
||||
|
||||
func populateMemory() {
|
||||
for idx in 1..<25 {
|
||||
let newItem = MoodEntry(context: viewContext)
|
||||
newItem.timestamp = Calendar.current.date(byAdding: .day, value: -idx, to: Date())
|
||||
newItem.moodValue = Int16(Mood.allValues.randomElement()!.rawValue)
|
||||
newItem.date = Calendar.current.date(byAdding: .day, value: -idx, to: Date())
|
||||
}
|
||||
do {
|
||||
try viewContext.save()
|
||||
} catch {
|
||||
// Replace this implementation with code to handle the error appropriately.
|
||||
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
|
||||
let nsError = error as NSError
|
||||
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
|
||||
}
|
||||
}
|
||||
|
||||
func fillInMissingDates() {
|
||||
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
|
||||
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
|
||||
let entries = try! viewContext.fetch(fetchRequest)
|
||||
|
||||
if let earliestDate = entries.last?.date {
|
||||
let diffInDays = Calendar.current.dateComponents([.day], from: earliestDate, to: Date()).day
|
||||
|
||||
for idx in 1..<diffInDays! {
|
||||
let searchDay = Calendar.current.date(byAdding: .day, value: -idx, to: Date())
|
||||
if entries.filter({ Calendar.current.isDate($0.date!, inSameDayAs:searchDay!) }).isEmpty {
|
||||
self.add(mood: .missing, forDate: searchDay!)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func clearDB() {
|
||||
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "MoodEntry")
|
||||
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
|
||||
|
||||
do {
|
||||
try viewContext.executeAndMergeChanges(using: deleteRequest)
|
||||
try viewContext.save()
|
||||
} catch let error as NSError {
|
||||
fatalError("Unresolved error \(error), \(error.userInfo)")
|
||||
}
|
||||
}
|
||||
|
||||
public func randomEntries(count: Int) -> [MoodEntry] {
|
||||
var entries = [MoodEntry]()
|
||||
|
||||
for idx in 0..<count {
|
||||
let newItem = MoodEntry(context: viewContext)
|
||||
newItem.timestamp = Calendar.current.date(byAdding: .day, value: -idx, to: Date())
|
||||
newItem.moodValue = Int16(Mood.allValues.randomElement()!.rawValue)
|
||||
newItem.date = Calendar.current.date(byAdding: .day, value: -idx, to: Date())
|
||||
entries.append(newItem)
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
let container: NSPersistentCloudKitContainer
|
||||
|
||||
|
||||
init(inMemory: Bool = false) {
|
||||
container = NSPersistentCloudKitContainer(name: "Feels")
|
||||
if inMemory {
|
||||
@@ -40,17 +149,31 @@ struct PersistenceController {
|
||||
if let error = error as NSError? {
|
||||
// Replace this implementation with code to handle the error appropriately.
|
||||
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
|
||||
|
||||
|
||||
/*
|
||||
Typical reasons for an error here include:
|
||||
* The parent directory does not exist, cannot be created, or disallows writing.
|
||||
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
|
||||
* The device is out of space.
|
||||
* The store could not be migrated to the current model version.
|
||||
Check the error message to determine what the actual problem was.
|
||||
*/
|
||||
Typical reasons for an error here include:
|
||||
* The parent directory does not exist, cannot be created, or disallows writing.
|
||||
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
|
||||
* The device is out of space.
|
||||
* The store could not be migrated to the current model version.
|
||||
Check the error message to determine what the actual problem was.
|
||||
*/
|
||||
fatalError("Unresolved error \(error), \(error.userInfo)")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
extension NSManagedObjectContext {
|
||||
|
||||
/// Executes the given `NSBatchDeleteRequest` and directly merges the changes to bring the given managed object context up to date.
|
||||
///
|
||||
/// - Parameter batchDeleteRequest: The `NSBatchDeleteRequest` to execute.
|
||||
/// - Throws: An error if anything went wrong executing the batch deletion.
|
||||
public func executeAndMergeChanges(using batchDeleteRequest: NSBatchDeleteRequest) throws {
|
||||
batchDeleteRequest.resultType = .resultTypeObjectIDs
|
||||
let result = try execute(batchDeleteRequest) as? NSBatchDeleteResult
|
||||
let changes: [AnyHashable: Any] = [NSDeletedObjectsKey: result?.result as? [NSManagedObjectID] ?? []]
|
||||
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [self])
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user