forked from UlricusR/iOS-EasyFPU
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIngredient+CoreDataClass.swift
More file actions
83 lines (65 loc) · 2.7 KB
/
Ingredient+CoreDataClass.swift
File metadata and controls
83 lines (65 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//
// Ingredient+CoreDataClass.swift
// EasyFPU
//
// Created by Ulrich Rüth on 05.11.20.
// Copyright © 2020 Ulrich Rüth. All rights reserved.
//
//
import Foundation
import CoreData
public class Ingredient: NSManagedObject {
public override var description: String {
name ?? NSLocalizedString("- Unnamed -", comment: "")
}
static func fetchAll(viewContext: NSManagedObjectContext = AppDelegate.viewContext) -> [Ingredient] {
let request: NSFetchRequest<Ingredient> = Ingredient.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
guard let ingredients = try? AppDelegate.viewContext.fetch(request) else {
return []
}
return ingredients
}
static func deleteAll(viewContext: NSManagedObjectContext = AppDelegate.viewContext) {
Ingredient.fetchAll(viewContext: viewContext).forEach({
viewContext.delete($0)
})
try? viewContext.save()
}
static func create(from foodItemVM: FoodItemViewModel) -> Ingredient {
let moc = AppDelegate.viewContext
// Create Ingredient
let cdIngredient = Ingredient(context: moc)
// Fill data
cdIngredient.amount = Int64(foodItemVM.amount)
cdIngredient.caloriesPer100g = foodItemVM.caloriesPer100g
cdIngredient.carbsPer100g = foodItemVM.carbsPer100g
cdIngredient.category = foodItemVM.category.rawValue
cdIngredient.favorite = foodItemVM.favorite
cdIngredient.id = foodItemVM.id
cdIngredient.name = foodItemVM.name
cdIngredient.sugarsPer100g = foodItemVM.sugarsPer100g
cdIngredient.foodItem = foodItemVM.cdFoodItem
// Save new Ingredient
try? moc.save()
return cdIngredient
}
static func create(from existingIngredient: Ingredient) -> Ingredient {
let moc = AppDelegate.viewContext
// Create Ingredient
let cdIngredient = Ingredient(context: moc)
cdIngredient.id = UUID()
// Fill data
cdIngredient.amount = existingIngredient.amount
cdIngredient.caloriesPer100g = existingIngredient.caloriesPer100g
cdIngredient.carbsPer100g = existingIngredient.carbsPer100g
cdIngredient.category = existingIngredient.category
cdIngredient.favorite = existingIngredient.favorite
cdIngredient.name = existingIngredient.name
cdIngredient.sugarsPer100g = existingIngredient.sugarsPer100g
cdIngredient.foodItem = existingIngredient.foodItem
// Save new Ingredient
try? moc.save()
return cdIngredient
}
}