Build an app with SwiftData

RSS for tag

Discuss the WWDC23 Build an app with SwiftData

Posts under wwdc2023-10154 tag

62 Posts

Post

Replies

Boosts

Views

Activity

SwiftData Query relationships not working
Overview I have 2 models: Deparment and Student Each Department can contain multiple students Each Student can only be in one Department I have DepartmentList, tapping on the department should take it to the StudentList which lists all students in the department Problem When I use Query in StudentList to filter only students for a specific department id, no students are shown. Questions: What should I do to list the students in a department? (see complete code below). let filter = #Predicate<Student> { student in student.department?.id == departmentID } let query = Query(filter: filter, sort: \.name) _students = query Complete code App @main struct SchoolApp: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: [Department.self, Student.self]) } } Department import Foundation import SwiftData @Model class Department { var id: UUID var name: String var students: [Student] init( id: UUID, name: String, students: [Student] = [] ) { self.id = id self.name = name self.students = students } } Student import Foundation import SwiftData @Model class Student { var id: UUID var name: String @Relationship(inverse: \Department.students) var department: Department? init( id: UUID, name: String, department: Department? = nil ) { self.id = id self.name = name self.department = department } } ContentView import SwiftUI struct ContentView: View { @State private var selectedDepartment: Department? var body: some View { NavigationSplitView { DepartmentList(selectedDepartment: $selectedDepartment) } detail: { if let department = selectedDepartment { StudentList(department: department) } else { Text("no department selected") } } .task { printStoreFilePath() } } private func printStoreFilePath() { let urls = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask) if let path = urls.map({ $0.path(percentEncoded: false) }).first { print("Storage: \(path)") } } } DepartmentList import SwiftUI import SwiftData struct DepartmentList: View { @Binding var selectedDepartment: Department? @Query(sort: \.name) private var departments: [Department] @Environment(\.modelContext) private var modelContext var body: some View { List(selection: $selectedDepartment) { ForEach(departments) { department in NavigationLink(value: department) { Text(department.name) } } } .toolbar { ToolbarItem { Button { addDepartment() } label: { Label("Add", systemImage: "plus") } } } } private func addDepartment() { guard let index = (1000..<10000).randomElement() else { return } let department = Department(id: UUID(), name: "Department \(index)") modelContext.insert(department) } } StudentList import SwiftUI import SwiftData struct StudentList: View { var department: Department @Query private var students: [Student] @Environment(\.modelContext) private var modelContext init(department: Department) { self.department = department let departmentID = department.id let filter = #Predicate<Student> { student in student.department?.id == departmentID } let query = Query(filter: filter, sort: \.name) _students = query } var body: some View { List { ForEach(students) { student in Text(student.name) } } .toolbar { ToolbarItem { Button { addStudent() } label: { Label("Add", systemImage: "plus") } } } } private func addStudent() { guard let index = (1000..<10000).randomElement() else { return } let student = Student( id: UUID(), name: "Student \(index)", department: department ) modelContext.insert(student) } }
10
4
4.1k
Jul ’23
Document and SwiftData ignore imported types
Hello there, I would like to bring attention to an issue I'm facing with SwiftData while attempting to create my own document type and a document-based app. It appears that there is a lack of support for imported types, and I'm unsure if this is a result of the beta version or an intentional omission. To reproduce the problem, please follow these steps: Create a document-based app with SwiftData enabled. Define your document type as "test" in the info.plist file. Include the "test" type in the list of exported type identifiers. Add a commonly used type such as "pdf" or "txt" to the list of imported type identifiers. Within the app's body, include a DocumentGroup with the content type set as "test." Currently, the app is capable of opening and creating new documents with the "test" type. However, I am unable to open common file types, such as images or text files. This limitation is a significant concern since the app often needs to handle these general file formats rather than being limited to its specific format. Thank you for your attention to this matter. I appreciate any assistance you can provide in resolving this issue. Best regards, Jeremy Vizzini
0
0
1.1k
Jun ’23
CKSyncEngine & SwiftData
I am working on a SwiftUI application that needs to sync data across multiple devices using CloudKit. I am trying to decide between two options: CKSyncEngine with a custom model SwiftData plus CloudKit container. This decision is crucial for me because the application I am developing is using tree structured data and the relationship between the data is very complex. I would appreciate your guidance on which option is better suited for my needs. One of the benefits of using SwiftData is that it has a lot of interesting features that can save me a lot of development time, such as automatic migrations, batch operations, predicates, sorting, grouping, etc. However, one of the drawbacks is that it may not be flexible enough to handle the complex data display logic that I need for my application. For example, I need to show different views depending on the level and type of the tree nodes, and I also need to perform some calculations and transformations on the data before displaying it. I am afraid that using SwiftData will lead to more complexity and uncertainty when implementing these features, and there may be performance issues as well. Another factor that I need to consider is the future support and development of these options. I believe SwiftData will have a good future because it is based on Apple's frameworks and technologies. However, I don't know if CKSyncEngine will be valued in the long run because it is a third-party framework that may not be updated or maintained regularly. In conclusion, I am still unsure whether to use CKSyncEngine or SwiftData for my SwiftUI application that needs CloudKit sync. Both options have their pros and cons, and I need to weigh them carefully according to my requirements and preferences. I would love to hear your opinion on this matter. Thank you for your time and attention.
5
0
1.9k
Jun ’23
Adopting SwiftData for a Core Data app - Error?
Hello everyone! I'm trying to run this project by Apple, but it doesn't let me, I'm trying to learn more about to swiftData... https://developer.apple.com/documentation/coredata/adopting_swiftdata_for_a_core_data_app On the code it says next: `@MainActor #Preview { AddBucketListItemView(trip: .preview) .modelContainer(PreviewSampleData.container) } But it show me next error, Type 'Trip' has no member 'preview' anybody knows how can I solved, thank you.
0
0
891
Jun ’23
Where are the companion Xcode projects for WWDC23 session 10154?
At 72 seconds in, the speaker says "This is a code-along. During this session, I will be building an app with you. Hit pause now, and download the companion Xcode projects: an archive with the prepared starting point, and the finished one." However, I cannot find these projects. I see a description, some links to other pages like these forums, some related videos, the transcript, and a series of code snippets displayed in the video, but no project files.
1
0
696
Jun ’23
Relationships are not persisted unless there is an inverse?
Hi, I encountered the issue, that unless an inverse relationship is modelled, the relationship is not persisted. This can be reproduced with the sample code below: Press the "Add Person" button twice Then press the "Add group" button You now can see that the group has to member, but once you restart the app the members a gone. Once an inverse relationship is added (see commented code) the relationships are persisted. Any idea if this is intended behaviour? import SwiftData import SwiftUI // MARK: - Person - @Model class Person { var name: String // uncomment to make it work @Relationship(.nullify) var group: Group? init(name: String) { self.name = name } } // MARK: - Group - @Model class Group { var name: String // uncomment to make it work @Relationship(.nullify, inverse: \Person.group) public var members: [Person] @Relationship(.nullify) public var members: [Person] // comment to make it work init(name: String) { self.name = name } } // MARK: - SD_PrototypingApp - @main struct SD_PrototypingApp: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: [Person.self, Group.self]) } } // MARK: - ContentView - struct ContentView: View { @Environment(\.modelContext) private var modelContext @Query private var groups: [Group] @Query private var persons: [Person] var body: some View { VStack { ForEach(groups) { group in Text("\(group.name): \(group.members.count)") } ForEach(persons) { person in Text("Person: \(person.name)") } Button { assert(persons.isEmpty == false) if groups.isEmpty { let group = Group(name: "Group A") group.members = persons modelContext.insert(group) try! modelContext.save() } } label: { Text("Add a group") } .disabled(!groups.isEmpty || persons.isEmpty) Button { let person = Person(name: "Person \(Int.random(in: 0 ... 1_000_000))") modelContext.insert(person) } label: { Text("Add Person") } } } }
0
1
1.5k
Jun ’23
SwiftData Sample Data for SwiftUI Previews
Has anyone figured out how to generate sample data for a Preview Container that contains relationships? I've tried numerous ways to get a relationship, but have not had any success. I've searched around the forms and the internet to see if I can find anything, but haven't had any luck. Here is what I have defined for my previewContainter and the sample data structure. I've followed the same pattern that is found in WWDC2023 Build an app with SwiftData. The books and tags are created just fine in memory, and in my SwiftUI previews, I can see these items. Here is what I currently have, but I have also tried running a query after SampleData.books.forEach(container.mainContext.insert(object: )) and then using one of the returned items for the relationship, but every query I perform in here returns an empty result. Am I barking up the wrong tree with my approach, or is this a known issue that I have not come across? @MainActor let previewContainer: ModelContainer = { do { let container = try ModelContainer( for: [Project.self, Recipe.self, Tag.self], ModelConfiguration(inMemory: true) ) // Add in sample data SampleData.books.forEach(container.mainContext.insert(object: )) SampleData.tags.forEach(container.mainContext.insert(object: )) SampleData.recipes.forEach(container.mainContext.insert(object: )) return container } catch { fatalError("Failed to create preview container") } }() struct SampleData { static let books: [Book] = { return (1...5).map({ Book(title: "Sample Book #\($0)") }) }() static let tags: [Tag] = { return (1...5).map({ Tag(name: "Sample Tag #\($0)") }) }() static let recipes: [Recipe] = { (1...5).map({ Recipe(name: "Sample Recipe #\($0)", book: Self.books.first!) }) }() } Thanks
8
1
4.9k
Jun ’23
"Compiler" card persists even after app code changed to use DocumentGroup
I made the changes described in the WWDC2023-10154 tutorial that were intended to allow the user to create a new (blank) document. However, every new document contains the "Compiler"/"Grace Hopper" card that was added to the persistent store in the earlier, non-document-based part of the video. I've tried a full clean and clearing derived data but I can't seem to get that card to go away. What am I missing? How can I make sure that new documents are created without any data?
3
2
641
Jun ’23
Predicate based on the relationship
I am trying to use SwiftData to perform a Query based on the name of the actor, which is inside a movie model. Here is the Movie model. @Model final class Movie { var title: String var year: Int @Relationship(.noAction, inverse: \Actor.movies) var actors: [Actor] = [] init(title: String, year: Int) { self.title = title self.year = year } } Here is my actual Query: _movies = Query(filter: #Predicate { $0.actors.contains(where: { $0.name.contains(actorName) }) }) But it returns nothing, even though I am passing actorName which exists in the movie.
3
1
1.9k
Jun ’23
Setting up XCTests for SwiftData model debugging
I am trying to create a document-based (macOS) app using SwiftUI and SwiftData. I'm trying to set up XCTests to validate my model behaviors. Clearly, I need to set up a container in my test class for my model objects. Failing to do so shows that SwiftData is trying: my app launches into the New Document dialog; if I dismiss it, the app fails with a "failed to find an active container" for my model object. Any pointer on setting up a container and context within XCTest is welcome. TIA
1
0
1.1k
Jun ’23
How to use a child context in SwiftData?
Hey there, for my recent projects I used CoreData for persistence. One nice feature I use all the time is the ability to create a child context for editing operations. When editing an entity in a form presented as a sheet, the changes made are only saved into the main context/parent context if the child context (I call this the editing context) is saved. Therefore dismissing an editing view results in destroying the child context and all the changes are discarded. Likewise when saving in the editing view, the changes will be proceeded to the parent context and persisted. Is there any possibility to get the same or equivalent behavior when using SwiftData. Or is there another way to model this kind of cases? All the best from Cologne, Germany!
2
1
2k
Jun ’23
SwiftData not persisted across runs on document-based app
Hello! I have followed steps outlined in Build an app with SwiftData to create a document-based app to create and save a set of flashcards. I have defined by model as follows: @Model final class Card { var createdAt: Date var front: String var back: String init(front: String, back: String, createdAt: Date = .now) { self.createdAt = createdAt self.front = front self.back = back } } I am loading a document group as described in the video: @main struct DeckApp: App { var body: some Scene { #if os(iOS) || os(macOS) DocumentGroup(editing: Card.self, contentType: .deck) { ContentView() } #else WindowGroup { ContentView() .modelContainer(for: Card.self) } #endif } } Moreover, I have defined document and exported types in info.plist: However, when I try to open a previously saved document, the items do not show up in the app, even though I can see some relevant strings in StoreContent-wal. Would anyone please be able to point me to something I must have missed? Thank you in advance.
1
0
633
Jun ’23
SwiftData Query relationships not working
Overview I have 2 models: Deparment and Student Each Department can contain multiple students Each Student can only be in one Department I have DepartmentList, tapping on the department should take it to the StudentList which lists all students in the department Problem When I use Query in StudentList to filter only students for a specific department id, no students are shown. Questions: What should I do to list the students in a department? (see complete code below). let filter = #Predicate<Student> { student in student.department?.id == departmentID } let query = Query(filter: filter, sort: \.name) _students = query Complete code App @main struct SchoolApp: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: [Department.self, Student.self]) } } Department import Foundation import SwiftData @Model class Department { var id: UUID var name: String var students: [Student] init( id: UUID, name: String, students: [Student] = [] ) { self.id = id self.name = name self.students = students } } Student import Foundation import SwiftData @Model class Student { var id: UUID var name: String @Relationship(inverse: \Department.students) var department: Department? init( id: UUID, name: String, department: Department? = nil ) { self.id = id self.name = name self.department = department } } ContentView import SwiftUI struct ContentView: View { @State private var selectedDepartment: Department? var body: some View { NavigationSplitView { DepartmentList(selectedDepartment: $selectedDepartment) } detail: { if let department = selectedDepartment { StudentList(department: department) } else { Text("no department selected") } } .task { printStoreFilePath() } } private func printStoreFilePath() { let urls = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask) if let path = urls.map({ $0.path(percentEncoded: false) }).first { print("Storage: \(path)") } } } DepartmentList import SwiftUI import SwiftData struct DepartmentList: View { @Binding var selectedDepartment: Department? @Query(sort: \.name) private var departments: [Department] @Environment(\.modelContext) private var modelContext var body: some View { List(selection: $selectedDepartment) { ForEach(departments) { department in NavigationLink(value: department) { Text(department.name) } } } .toolbar { ToolbarItem { Button { addDepartment() } label: { Label("Add", systemImage: "plus") } } } } private func addDepartment() { guard let index = (1000..<10000).randomElement() else { return } let department = Department(id: UUID(), name: "Department \(index)") modelContext.insert(department) } } StudentList import SwiftUI import SwiftData struct StudentList: View { var department: Department @Query private var students: [Student] @Environment(\.modelContext) private var modelContext init(department: Department) { self.department = department let departmentID = department.id let filter = #Predicate<Student> { student in student.department?.id == departmentID } let query = Query(filter: filter, sort: \.name) _students = query } var body: some View { List { ForEach(students) { student in Text(student.name) } } .toolbar { ToolbarItem { Button { addStudent() } label: { Label("Add", systemImage: "plus") } } } } private func addStudent() { guard let index = (1000..<10000).randomElement() else { return } let student = Student( id: UUID(), name: "Student \(index)", department: department ) modelContext.insert(student) } }
Replies
10
Boosts
4
Views
4.1k
Activity
Jul ’23
Document and SwiftData ignore imported types
Hello there, I would like to bring attention to an issue I'm facing with SwiftData while attempting to create my own document type and a document-based app. It appears that there is a lack of support for imported types, and I'm unsure if this is a result of the beta version or an intentional omission. To reproduce the problem, please follow these steps: Create a document-based app with SwiftData enabled. Define your document type as "test" in the info.plist file. Include the "test" type in the list of exported type identifiers. Add a commonly used type such as "pdf" or "txt" to the list of imported type identifiers. Within the app's body, include a DocumentGroup with the content type set as "test." Currently, the app is capable of opening and creating new documents with the "test" type. However, I am unable to open common file types, such as images or text files. This limitation is a significant concern since the app often needs to handle these general file formats rather than being limited to its specific format. Thank you for your attention to this matter. I appreciate any assistance you can provide in resolving this issue. Best regards, Jeremy Vizzini
Replies
0
Boosts
0
Views
1.1k
Activity
Jun ’23
CKSyncEngine & SwiftData
I am working on a SwiftUI application that needs to sync data across multiple devices using CloudKit. I am trying to decide between two options: CKSyncEngine with a custom model SwiftData plus CloudKit container. This decision is crucial for me because the application I am developing is using tree structured data and the relationship between the data is very complex. I would appreciate your guidance on which option is better suited for my needs. One of the benefits of using SwiftData is that it has a lot of interesting features that can save me a lot of development time, such as automatic migrations, batch operations, predicates, sorting, grouping, etc. However, one of the drawbacks is that it may not be flexible enough to handle the complex data display logic that I need for my application. For example, I need to show different views depending on the level and type of the tree nodes, and I also need to perform some calculations and transformations on the data before displaying it. I am afraid that using SwiftData will lead to more complexity and uncertainty when implementing these features, and there may be performance issues as well. Another factor that I need to consider is the future support and development of these options. I believe SwiftData will have a good future because it is based on Apple's frameworks and technologies. However, I don't know if CKSyncEngine will be valued in the long run because it is a third-party framework that may not be updated or maintained regularly. In conclusion, I am still unsure whether to use CKSyncEngine or SwiftData for my SwiftUI application that needs CloudKit sync. Both options have their pros and cons, and I need to weigh them carefully according to my requirements and preferences. I would love to hear your opinion on this matter. Thank you for your time and attention.
Replies
5
Boosts
0
Views
1.9k
Activity
Jun ’23
FlashCardSample new card issue
I was able to add a new card. I added 3 cards. When I clicked on second card or third card, it showed the first card only. Must be some index issue with view. Please let me know. Thanks!
Replies
1
Boosts
0
Views
860
Activity
Jun ’23
Adopting SwiftData for a Core Data app - Error?
Hello everyone! I'm trying to run this project by Apple, but it doesn't let me, I'm trying to learn more about to swiftData... https://developer.apple.com/documentation/coredata/adopting_swiftdata_for_a_core_data_app On the code it says next: `@MainActor #Preview { AddBucketListItemView(trip: .preview) .modelContainer(PreviewSampleData.container) } But it show me next error, Type 'Trip' has no member 'preview' anybody knows how can I solved, thank you.
Replies
0
Boosts
0
Views
891
Activity
Jun ’23
Companion Xcode project
Don't see a link to download the Xcode project, starter and complete? How can I get it? Thanks Bob
Replies
2
Boosts
1
Views
832
Activity
Jun ’23
Is SwiftData Secure?
How secure storing the data using SwiftData? What encryption mechanism is it used to store data? Our project has a requirement to shore data using AES 256 encryption.
Replies
2
Boosts
0
Views
2.2k
Activity
Jun ’23
Swift Data for one off data storage
What is the best way to use swift data to store one off data models? For example an application state that you want to be persisted across application launches. The only examples I've seen use arrays of items which wouldn't work for having just one application state. Is it possible to query just one item?
Replies
3
Boosts
0
Views
2.2k
Activity
Jun ’23
Where are the companion Xcode projects for WWDC23 session 10154?
At 72 seconds in, the speaker says "This is a code-along. During this session, I will be building an app with you. Hit pause now, and download the companion Xcode projects: an archive with the prepared starting point, and the finished one." However, I cannot find these projects. I see a description, some links to other pages like these forums, some related videos, the transcript, and a series of code snippets displayed in the video, but no project files.
Replies
1
Boosts
0
Views
696
Activity
Jun ’23
Relationships are not persisted unless there is an inverse?
Hi, I encountered the issue, that unless an inverse relationship is modelled, the relationship is not persisted. This can be reproduced with the sample code below: Press the "Add Person" button twice Then press the "Add group" button You now can see that the group has to member, but once you restart the app the members a gone. Once an inverse relationship is added (see commented code) the relationships are persisted. Any idea if this is intended behaviour? import SwiftData import SwiftUI // MARK: - Person - @Model class Person { var name: String // uncomment to make it work @Relationship(.nullify) var group: Group? init(name: String) { self.name = name } } // MARK: - Group - @Model class Group { var name: String // uncomment to make it work @Relationship(.nullify, inverse: \Person.group) public var members: [Person] @Relationship(.nullify) public var members: [Person] // comment to make it work init(name: String) { self.name = name } } // MARK: - SD_PrototypingApp - @main struct SD_PrototypingApp: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: [Person.self, Group.self]) } } // MARK: - ContentView - struct ContentView: View { @Environment(\.modelContext) private var modelContext @Query private var groups: [Group] @Query private var persons: [Person] var body: some View { VStack { ForEach(groups) { group in Text("\(group.name): \(group.members.count)") } ForEach(persons) { person in Text("Person: \(person.name)") } Button { assert(persons.isEmpty == false) if groups.isEmpty { let group = Group(name: "Group A") group.members = persons modelContext.insert(group) try! modelContext.save() } } label: { Text("Add a group") } .disabled(!groups.isEmpty || persons.isEmpty) Button { let person = Person(name: "Person \(Int.random(in: 0 ... 1_000_000))") modelContext.insert(person) } label: { Text("Add Person") } } } }
Replies
0
Boosts
1
Views
1.5k
Activity
Jun ’23
SwiftData Sample Data for SwiftUI Previews
Has anyone figured out how to generate sample data for a Preview Container that contains relationships? I've tried numerous ways to get a relationship, but have not had any success. I've searched around the forms and the internet to see if I can find anything, but haven't had any luck. Here is what I have defined for my previewContainter and the sample data structure. I've followed the same pattern that is found in WWDC2023 Build an app with SwiftData. The books and tags are created just fine in memory, and in my SwiftUI previews, I can see these items. Here is what I currently have, but I have also tried running a query after SampleData.books.forEach(container.mainContext.insert(object: )) and then using one of the returned items for the relationship, but every query I perform in here returns an empty result. Am I barking up the wrong tree with my approach, or is this a known issue that I have not come across? @MainActor let previewContainer: ModelContainer = { do { let container = try ModelContainer( for: [Project.self, Recipe.self, Tag.self], ModelConfiguration(inMemory: true) ) // Add in sample data SampleData.books.forEach(container.mainContext.insert(object: )) SampleData.tags.forEach(container.mainContext.insert(object: )) SampleData.recipes.forEach(container.mainContext.insert(object: )) return container } catch { fatalError("Failed to create preview container") } }() struct SampleData { static let books: [Book] = { return (1...5).map({ Book(title: "Sample Book #\($0)") }) }() static let tags: [Tag] = { return (1...5).map({ Tag(name: "Sample Tag #\($0)") }) }() static let recipes: [Recipe] = { (1...5).map({ Recipe(name: "Sample Recipe #\($0)", book: Self.books.first!) }) }() } Thanks
Replies
8
Boosts
1
Views
4.9k
Activity
Jun ’23
"Compiler" card persists even after app code changed to use DocumentGroup
I made the changes described in the WWDC2023-10154 tutorial that were intended to allow the user to create a new (blank) document. However, every new document contains the "Compiler"/"Grace Hopper" card that was added to the persistent store in the earlier, non-document-based part of the video. I've tried a full clean and clearing derived data but I can't seem to get that card to go away. What am I missing? How can I make sure that new documents are created without any data?
Replies
3
Boosts
2
Views
641
Activity
Jun ’23
Predicate based on the relationship
I am trying to use SwiftData to perform a Query based on the name of the actor, which is inside a movie model. Here is the Movie model. @Model final class Movie { var title: String var year: Int @Relationship(.noAction, inverse: \Actor.movies) var actors: [Actor] = [] init(title: String, year: Int) { self.title = title self.year = year } } Here is my actual Query: _movies = Query(filter: #Predicate { $0.actors.contains(where: { $0.name.contains(actorName) }) }) But it returns nothing, even though I am passing actorName which exists in the movie.
Replies
3
Boosts
1
Views
1.9k
Activity
Jun ’23
Setting up XCTests for SwiftData model debugging
I am trying to create a document-based (macOS) app using SwiftUI and SwiftData. I'm trying to set up XCTests to validate my model behaviors. Clearly, I need to set up a container in my test class for my model objects. Failing to do so shows that SwiftData is trying: my app launches into the New Document dialog; if I dismiss it, the app fails with a "failed to find an active container" for my model object. Any pointer on setting up a container and context within XCTest is welcome. TIA
Replies
1
Boosts
0
Views
1.1k
Activity
Jun ’23
Error after adding previewContainer during code-along
I am getting this error in my preview: CompileDylibError: Failed to build ContentView.swift Compiling failed: main actor-isolated let 'previewContainer' can not be referenced from a non-isolated context I don't know enough about @MainActor to figure this out.
Replies
6
Boosts
8
Views
1.8k
Activity
Jun ’23
How to use a child context in SwiftData?
Hey there, for my recent projects I used CoreData for persistence. One nice feature I use all the time is the ability to create a child context for editing operations. When editing an entity in a form presented as a sheet, the changes made are only saved into the main context/parent context if the child context (I call this the editing context) is saved. Therefore dismissing an editing view results in destroying the child context and all the changes are discarded. Likewise when saving in the editing view, the changes will be proceeded to the parent context and persisted. Is there any possibility to get the same or equivalent behavior when using SwiftData. Or is there another way to model this kind of cases? All the best from Cologne, Germany!
Replies
2
Boosts
1
Views
2k
Activity
Jun ’23
Does the build along require macOS Sonoma?
Hi, does the build along require macOS Sonoma or can one simply use macOS 13.4 Ventura with Xcode 15 Beta?
Replies
1
Boosts
2
Views
631
Activity
Jun ’23
SwiftData Journal Mode
With Core Data you can control the journal mode as follows: let dictionaryOptions = [NSSQLitePragmasOption : ["journal_mode" : "DELETE"]] Is there a SwiftData equivalent?
Replies
0
Boosts
0
Views
849
Activity
Jun ’23
Previews working correctly for sample starter project?
Failed to launch My Mac previews. Works fine for iPhone and iPad. Anyone having similar issues?
Replies
1
Boosts
1
Views
348
Activity
Jun ’23
SwiftData not persisted across runs on document-based app
Hello! I have followed steps outlined in Build an app with SwiftData to create a document-based app to create and save a set of flashcards. I have defined by model as follows: @Model final class Card { var createdAt: Date var front: String var back: String init(front: String, back: String, createdAt: Date = .now) { self.createdAt = createdAt self.front = front self.back = back } } I am loading a document group as described in the video: @main struct DeckApp: App { var body: some Scene { #if os(iOS) || os(macOS) DocumentGroup(editing: Card.self, contentType: .deck) { ContentView() } #else WindowGroup { ContentView() .modelContainer(for: Card.self) } #endif } } Moreover, I have defined document and exported types in info.plist: However, when I try to open a previously saved document, the items do not show up in the app, even though I can see some relevant strings in StoreContent-wal. Would anyone please be able to point me to something I must have missed? Thank you in advance.
Replies
1
Boosts
0
Views
633
Activity
Jun ’23