Post

Replies

Boosts

Views

Activity

Correct way to remove arrays containing model objects in SwiftData
Are there any differences (either performance or memory considerations) between removing an array of model objects directly using .removeAll() vs using modelContext? Or, are they identical? Attached below is an example to better illustrate the question (i.e., First Way vs Second Way) // Model Definition @Model class GroupOfPeople { let groupName: String @Relationship(deleteRule: .cascade, inverse: \Person.group) var people: [Person] = [] init() { ... } } @Model class Person { let name: String var group: GroupOfPeople? init() { ... } } // First way struct DemoView: View { @Query private groups: [GroupOfPeople] var body: some View { List(groups) { group in DetailView(group: group) } } } struct DetailView: View { let group: GroupOfPeople var body: some View { Button("Delete All Participants") { group.people.removeAll() } } // Second way struct DemoView: View { @Query private groups: [GroupOfPeople] var body: some View { List(groups) { group in DetailView(group: group) } } } struct DetailView: View { @Environment(\.modelContext) private var context let group: GroupOfPeople var body: some View { Button("Delete All Participants") { context.delete(model: Person.self, where: #Predicate { $0.group.name == group.name }) } // assuming group names are unique. more of making a point using modelContext instead }
0
0
152
2w
Scale contextMenu preview size to containing content
Hi! I have a multi-line string I'd like to display as text in a long-press preview (using .contextMenu). However, text after 3rd or 4th linebreak (\n) gets clipped. The intended effect is to have the minimum preview size that can fit all of the text. Tried .frame(maxWidth: .infinity, maxHeight: .infinity) on Text() but it didn't have any effect. The only modifier that somewhat works is .containerRelativeFrame([.horizontal, .vertical]) but this gives the maximum preview size, instead of minimum. Any suggestions? TIA. struct RedditView: View { @State private var text = "AAAAAAAAAAAAAAAAAAAAAA?\n\nBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\nCCCCCCCCCCCCCCCCCCCCCCCCCC" var body: some View { Text("Long press this") .frame(width: 300, height: 100) .contentShape(.rect) .border(Color.blue) .contextMenu(menuItems: { Button { // do something } label: { Label { Text("Edit") } icon: { Image(systemName: "pencil") } } }, preview: { Text(text) // .frame(maxWidth: .infinity, maxHeight: .infinity) .multilineTextAlignment(.center) .padding() //.containerRelativeFrame([.horizontal, .vertical]) } ) } }
0
0
308
Sep ’24