-
Notifications
You must be signed in to change notification settings - Fork 3
/
ContentView.swift
62 lines (53 loc) · 2 KB
/
ContentView.swift
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
//
// ContentView.swift
// P12G CoreDataProject
//
// Created by Julian Moorhouse on 03/04/2021.
//
import CoreData
import SwiftUI
struct ContentView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: Country.entity(), sortDescriptors: []) var countries: FetchedResults<Country>
var body: some View {
VStack {
List {
ForEach(countries, id: \.self) { country in
Section(header: Text(country.wrappedFullName)) {
ForEach(country.candyArray, id: \.self) { candy in
Text(candy.wrappedName)
}
}
}
}
Button("Add") {
let candy1 = Candy(context: self.moc)
candy1.name = "Mars"
candy1.origin = Country(context: self.moc)
candy1.origin?.shortName = "UK"
candy1.origin?.fullName = "United Kingdom"
let candy2 = Candy(context: self.moc)
candy2.name = "KitKat"
candy2.origin = Country(context: self.moc)
candy2.origin?.shortName = "UK"
candy2.origin?.fullName = "United Kingdom"
let candy3 = Candy(context: self.moc)
candy3.name = "Twix"
candy3.origin = Country(context: self.moc)
candy3.origin?.shortName = "UK"
candy3.origin?.fullName = "United Kingdom"
let candy4 = Candy(context: self.moc)
candy4.name = "Toblerone"
candy4.origin = Country(context: self.moc)
candy4.origin?.shortName = "CH"
candy4.origin?.fullName = "Switzerland"
try? self.moc.save()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}