Post

Replies

Boosts

Views

Activity

Reply to SwiftData Sample Data for SwiftUI Previews
You can do an initial query for related objects but as of Xcode 15 beta 1 it won't automatically update so that could be your problem. Unfortunately it is still terrible syntax for using a predicate with supplied data as it was for @FetchRequest, they really need to switch from property wrappers to view modifiers for fetching so we can pass in parameters that can dynamically change from parent Views and from States in current View. 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.objectID let predicate = #Predicate<Student> { student in student.department?.objectID == departmentID } // let query = Query(filter: filter, sort: \.name) // let fd = FetchDescriptor<Student>(predicate: predicate, sortBy: [SortDescriptor(\.name)]) let query = Query(fd, animation: .default) _students = query // nasty to have to implement and init and use underscore syntax to implement this simple feature }
Jun ’23
Reply to Observation and MainActor
Your use of URLSession and @StateObject likely means you are attempting to do async networking in this object so it shouldn't be @MainActor because you'll want your async funcs to run on background threads not on the main thread. Also, when switching from @ObservedObject to @Observable you no longer need to use Task { @MainActor in when setting vars (@Published in case of @ObservedObject) with the results of the network calls.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Jun ’23
Reply to Xcode 15 beta 5 error: Invalid Swift parseable output message (malformed JSON)
Same problem here, it happens when I try this in my AppIntent: @Parameter(title: "Image") var file: IntentFile error: Invalid Swift parseable output message (malformed JSON): `1` (in target 'IntentTest2' from project 'IntentTest2') error: Invalid Swift parseable output message (malformed JSON): `{ "kind": "finished", ` (in target 'IntentTest2' from project 'IntentTest2') "name": "compile", "pid": 64892, "process": { "real_pid": 64893 }, "exit-status": 0 } Command SwiftCompile emitted errors but did not return a nonzero exit code to indicate failure
Topic: Programming Languages SubTopic: Swift Tags:
Aug ’23
Reply to Disable automatic iCloud sync with SwiftData
Same problem here, ModelConfiguration(cloudKitDatabase: .none) still uses CloudKit and the app crashes in my case with: CloudKit integration requires that all relationships be optional, the following are not: Contact: addresses Have to disable CloudKit capability to get it to run which is a terrible workaround. Submitted FB13209319 referencing FB12276416
Sep ’23
Reply to @State ViewModel memory leak in iOS 17 (new Observable)
The solution is don't use view model objects! You have to learn the View struct which is designed to hold your view data in a memory efficient hierarchy. It has a lot of magical features like dependency tracking and change detection which you just have to learn to use SwiftUI effectively. @Observable is for model data it won't work for view data. You might get close to implementing the same behaviour as the View struct but you'll eventually get stuck so it is a complete waste of time. Correct SwiftUI code would look like this: struct ModalConfig { var isPresented = false var otherVar = "" mutating func present() { isPresented = true otherVar = "" } mutating func dismiss() { isPresented = false } } struct ModalView: View { @Binding var config: ModalConfig var body: some View { ZStack { Color.yellow .ignoresSafeArea() Button("Close") { config.dismiss() } } } } struct ContentView: View { @State var config = ModalConfig() var body: some View { Button("Present sheet modally") { config.present() } .sheet(isPresented: $config.isPresented) { ModalView(config: $config) } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Oct ’23
Reply to When SwiftUI View is Equatable - questions...
∙View can conform to Equatable... True, .equatable() is no longer required, not sure what version that changed in. . ∙When view contains @ObservedObject... False, regardless of the outcome of ==, body is always called when any @Published property of the object changes or objectWillChange is published. . ∙Does view, that is Equatable, need to care about equality of its subviews.. No, a subview will just follow the same algorithm. Best to only init a View with the data it actually needs and uses in its body to keep invalidation tight. . ∙When view returns true on equality check... True, if you returned true from == but had @Environment(\.calendar) var calendar and the calendar changed the body would still be called. This is the same behaviour as @ObservedObject in the 2nd question. . ∙When the observed object conforms to Equatable... In my testing the if an ObservedObject conformed to Equatable the == func was never called. My test code: import SwiftUI import Combine struct ViewTest { class MyObject: ObservableObject, Equatable { static func == (lhs: ViewTest.MyObject, rhs: ViewTest.MyObject) -> Bool { // not called let x = lhs.counter1 == rhs.counter1 && lhs.counter2 == rhs.counter2 return x } @Published var counter1 = 0 @Published var counter2 = 0 func inc() { counter1 += 1 } } struct ContentView: View { @State var counter = 0 @State var counter2 = 0 @StateObject var object = MyObject() var body: some View { Form { Button("Increment \(counter)") { counter += 1 } Button("Increment \(counter2)") { counter2 += 1 } // ContentView2(x: counter) { [c = counter] in // print("\(c)") // body is called once when counter2 is changed the first time (once after every time if it has the onReceive // } ContentView2(x: counter2) .environment(\.calendar, ((counter % 2 == 0) ? Calendar.current : Calendar(identifier: .chinese))) //{ // print("\(self.counter)") // body called every time counter2 is changed // } // .equatable() } } } struct ContentView2: View, Equatable { // @Environment(\.managedObjectContext) var context //@State var counter = 0 //@ObservedObject var object: MyObject @Environment(\.calendar) var calendar let x: Int // let y: () -> () // if the closure passed in does somethiung with self then body is always called. static func == (lhs: Self, rhs: Self) -> Bool { let result = lhs.x == rhs.x //&& lhs.object.counter2 == rhs.object.counter2 return result } var body: some View { let _ = Self._printChanges() HStack { Text("ff") Button("Button") { //y() } } // .onReceive(Just(0)) { _ in // causes body to be called // print("") // } // .task { // counter = 0 // }.onChange(of: x) { a in // // } // .onAppear { // counter = 0 // } } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Nov ’23
Reply to Set 12 vs 24 hour with the new date formatting API in iOS 15
It seems you have to override the environment locale and switch between one that defaults to am/pm (like GB) and one that is 24hr (like US), e.g. @State var is12h = false let date = Date() ... Text(date, format: .dateTime.hour(.twoDigits(amPM: .abbreviated)).minute(.twoDigits)) .environment(\.locale, Locale(identifier: is12h ? "en_GB" : "en_US")) ... 11:01PM 23:01
Topic: App & System Services SubTopic: General Tags:
Nov ’23
Reply to Does ModelContext fetch() return an auto-updating results array?
edit - "I suppose we would call fetch() from onAppear and onChanged" I meant fetch() is called from computed property that is used in a ForEach.
Replies
Boosts
Views
Activity
Jun ’23
Reply to SwiftData Sample Data for SwiftUI Previews
You can do an initial query for related objects but as of Xcode 15 beta 1 it won't automatically update so that could be your problem. Unfortunately it is still terrible syntax for using a predicate with supplied data as it was for @FetchRequest, they really need to switch from property wrappers to view modifiers for fetching so we can pass in parameters that can dynamically change from parent Views and from States in current View. 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.objectID let predicate = #Predicate<Student> { student in student.department?.objectID == departmentID } // let query = Query(filter: filter, sort: \.name) // let fd = FetchDescriptor<Student>(predicate: predicate, sortBy: [SortDescriptor(\.name)]) let query = Query(fd, animation: .default) _students = query // nasty to have to implement and init and use underscore syntax to implement this simple feature }
Replies
Boosts
Views
Activity
Jun ’23
Reply to How to use transformable in SwiftData?
It is probably a bad idea to try to store a UI type in the model. It would be better to store a model type in the model and then transform it into a UI type using the SwiftUI View hierarchy, i.e. using a computed property called from body that returns a Color struct created from the model type.
Replies
Boosts
Views
Activity
Jun ’23
Reply to Reading Codable properties raised a fatal error.
Better to store your own location type and transform it into a CLLocationCoordinate2D when you need one. If you're using SwiftUI you can use the View hierarchy to transform from your model type to that type, via a computed property called from body. That way it will only be transformed when it has changed.
Replies
Boosts
Views
Activity
Jun ’23
Reply to Swift Data for one off data storage
Better to use @AppStorage for that
Replies
Boosts
Views
Activity
Jun ’23
Reply to Observation and MainActor
Your use of URLSession and @StateObject likely means you are attempting to do async networking in this object so it shouldn't be @MainActor because you'll want your async funcs to run on background threads not on the main thread. Also, when switching from @ObservedObject to @Observable you no longer need to use Task { @MainActor in when setting vars (@Published in case of @ObservedObject) with the results of the network calls.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Jun ’23
Reply to Xcode 15 beta 2: can't install iOS 17.0 beta 2 or visionOS 1.0
Same problem here.
Topic: Community SubTopic: Apple Developers Tags:
Replies
Boosts
Views
Activity
Jun ’23
Reply to Incorrect Metadata.appintents with Xcode 14.3?
I have the same error "The action “Demo Action” could not run because an internal error occurred." in Xcode 15 beta 5. I resolved it by making a Multiplatform app template instead of a macOS.
Topic: App & System Services SubTopic: General Tags:
Replies
Boosts
Views
Activity
Aug ’23
Reply to Xcode 15 beta 5 error: Invalid Swift parseable output message (malformed JSON)
Same problem here, it happens when I try this in my AppIntent: @Parameter(title: "Image") var file: IntentFile error: Invalid Swift parseable output message (malformed JSON): `1` (in target 'IntentTest2' from project 'IntentTest2') error: Invalid Swift parseable output message (malformed JSON): `{ "kind": "finished", ` (in target 'IntentTest2' from project 'IntentTest2') "name": "compile", "pid": 64892, "process": { "real_pid": 64893 }, "exit-status": 0 } Command SwiftCompile emitted errors but did not return a nonzero exit code to indicate failure
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Aug ’23
Reply to xcode 15 Beta 5 iOS Simulators... Springboard Crash & High CPU
Xcode Version 15.0 beta 7 (15A5229h) has the same problem. It's burning my legs!
Replies
Boosts
Views
Activity
Aug ’23
Reply to Disable automatic iCloud sync with SwiftData
Same problem here, ModelConfiguration(cloudKitDatabase: .none) still uses CloudKit and the app crashes in my case with: CloudKit integration requires that all relationships be optional, the following are not: Contact: addresses Have to disable CloudKit capability to get it to run which is a terrible workaround. Submitted FB13209319 referencing FB12276416
Replies
Boosts
Views
Activity
Sep ’23
Reply to @State ViewModel memory leak in iOS 17 (new Observable)
The solution is don't use view model objects! You have to learn the View struct which is designed to hold your view data in a memory efficient hierarchy. It has a lot of magical features like dependency tracking and change detection which you just have to learn to use SwiftUI effectively. @Observable is for model data it won't work for view data. You might get close to implementing the same behaviour as the View struct but you'll eventually get stuck so it is a complete waste of time. Correct SwiftUI code would look like this: struct ModalConfig { var isPresented = false var otherVar = "" mutating func present() { isPresented = true otherVar = "" } mutating func dismiss() { isPresented = false } } struct ModalView: View { @Binding var config: ModalConfig var body: some View { ZStack { Color.yellow .ignoresSafeArea() Button("Close") { config.dismiss() } } } } struct ContentView: View { @State var config = ModalConfig() var body: some View { Button("Present sheet modally") { config.present() } .sheet(isPresented: $config.isPresented) { ModalView(config: $config) } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Oct ’23
Reply to Swift Concurrency, Core Data, "partially thread-safe" types & Sendable conformance
I wouldn't put a core data stack in an actor since it is designed to be used from the main actor. You could perhaps create a background context in an actor though.
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Oct ’23
Reply to When SwiftUI View is Equatable - questions...
∙View can conform to Equatable... True, .equatable() is no longer required, not sure what version that changed in. . ∙When view contains @ObservedObject... False, regardless of the outcome of ==, body is always called when any @Published property of the object changes or objectWillChange is published. . ∙Does view, that is Equatable, need to care about equality of its subviews.. No, a subview will just follow the same algorithm. Best to only init a View with the data it actually needs and uses in its body to keep invalidation tight. . ∙When view returns true on equality check... True, if you returned true from == but had @Environment(\.calendar) var calendar and the calendar changed the body would still be called. This is the same behaviour as @ObservedObject in the 2nd question. . ∙When the observed object conforms to Equatable... In my testing the if an ObservedObject conformed to Equatable the == func was never called. My test code: import SwiftUI import Combine struct ViewTest { class MyObject: ObservableObject, Equatable { static func == (lhs: ViewTest.MyObject, rhs: ViewTest.MyObject) -> Bool { // not called let x = lhs.counter1 == rhs.counter1 && lhs.counter2 == rhs.counter2 return x } @Published var counter1 = 0 @Published var counter2 = 0 func inc() { counter1 += 1 } } struct ContentView: View { @State var counter = 0 @State var counter2 = 0 @StateObject var object = MyObject() var body: some View { Form { Button("Increment \(counter)") { counter += 1 } Button("Increment \(counter2)") { counter2 += 1 } // ContentView2(x: counter) { [c = counter] in // print("\(c)") // body is called once when counter2 is changed the first time (once after every time if it has the onReceive // } ContentView2(x: counter2) .environment(\.calendar, ((counter % 2 == 0) ? Calendar.current : Calendar(identifier: .chinese))) //{ // print("\(self.counter)") // body called every time counter2 is changed // } // .equatable() } } } struct ContentView2: View, Equatable { // @Environment(\.managedObjectContext) var context //@State var counter = 0 //@ObservedObject var object: MyObject @Environment(\.calendar) var calendar let x: Int // let y: () -> () // if the closure passed in does somethiung with self then body is always called. static func == (lhs: Self, rhs: Self) -> Bool { let result = lhs.x == rhs.x //&& lhs.object.counter2 == rhs.object.counter2 return result } var body: some View { let _ = Self._printChanges() HStack { Text("ff") Button("Button") { //y() } } // .onReceive(Just(0)) { _ in // causes body to be called // print("") // } // .task { // counter = 0 // }.onChange(of: x) { a in // // } // .onAppear { // counter = 0 // } } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Nov ’23
Reply to Set 12 vs 24 hour with the new date formatting API in iOS 15
It seems you have to override the environment locale and switch between one that defaults to am/pm (like GB) and one that is 24hr (like US), e.g. @State var is12h = false let date = Date() ... Text(date, format: .dateTime.hour(.twoDigits(amPM: .abbreviated)).minute(.twoDigits)) .environment(\.locale, Locale(identifier: is12h ? "en_GB" : "en_US")) ... 11:01PM 23:01
Topic: App & System Services SubTopic: General Tags:
Replies
Boosts
Views
Activity
Nov ’23