Post

Replies

Boosts

Views

Activity

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.4k
Jun ’23
actors, SwiftUI and @Published
Hi, is there a way that an actor can have a @MainActor @Published annotated property which is then consumed by a SwiftUI View "as usual"? Currently this: @Published @MainActor public private(set) var state: State = .initial gives me the following error when trying to access it from with a SwiftUI View: "Actor-isolated property '$state' can only be referenced from inside the actor" I guess I understand where the error is coming from, but I wonder if there's a way to publish properties from actors and be able to make sure they are updated on the main thread by annotating them with @MainActor.
1
0
4.0k
Aug ’21
CoreData relationships in a child context are not isolated?
Hi, I am using a child NSManagedContext trying to isolate changes to a NSManagedObject from changes done to the same object in the parent NSManagedObjectContext. This works fine for normal properties, but any changes to relationships performed on the object in the parent context will show up immediately in the child object as well. Is this the intended behavior? If yes is there a way to create an "isolated" version of an NSManagedObject? Thanks in advance for any hints! Cheers, Michael
1
0
1.4k
Sep ’21
Using actors in a SwiftUI .task
Hi, having the concurrency checks (-Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks-Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks) enabled I always get this warning, when trying to access/use an actor in a SwiftUI .task: "Cannot use parameter 'self' with a non-sendable type 'ContentView' from concurrently-executed code". What would be a correct implementation? Here's a minimal code-sample which produces this warning: import SwiftUI struct ContentView: View { @State var someVar = 5 var a1 = A1() var body: some View { Text("Hello, world!") .padding() .task { await a1.doSomething() } } } public actor A1 { func doSomething() { print("Hello") } }
1
0
2.3k
Feb ’22
Is migration working for anyone on Xcode beta6?
Hi, I am trying my first SwiftData migration, but my custom migration stage never gets called. Since I am not sure if this is a bug with the current beta of if I am "holding it wrong" I was wondering, if anybody got migration working (their MigrationStage.custom called)? Would be great, if you could just let me know, if you got it working or running into the same issue! :-) Thank you! Cheers, Michael
1
0
1.1k
Aug ’23
Limitations for attributes in SwiftData models?
Hi, is there any description/documentation about what can not be used as SwiftData attributes? I do not mean things which cause issues at compile time, like having a type which is not Codeable. But rather I am looking for info which things to avoid, if you do not want to run into application crashes in modelContext.save(). Like for example having an enum which as an optional associated value as an attribute type (crashes on save is the associated value is nil). Anybody seen any documentation about that? Or tech notes? Thanks in advance for any hints :-). Cheers, Michael
1
1
445
Sep ’24
ScrollView not working properly on macOS?
Hi, I have a very simple program (see below) with some Views in an HStack, which is within a ScrollView. This works fine on iOS, but on macOS nothing scrolls. Am I missing something? Shouldn't it just scroll? import SwiftUI struct ContentView: View { 	var body: some View { 		ScrollView(.horizontal, showsIndicators: true) { 			HStack { 				ItemView(n: 1) 				ItemView(n: 2) 				ItemView(n: 3) 				ItemView(n: 4) 				ItemView(n: 5) 			} 		} 		.frame(minWidth: 350, maxWidth: 800, minHeight: 250, maxHeight: 250, alignment: .center) 	} } struct ContentView_Previews: PreviewProvider { 	static var previews: some View { 		ContentView() 	} } struct ItemView: View { 	var n: Int 	 	var body: some View { 		Rectangle() 			.frame(width: 300, height: 200) 			.overlay(Text("\(n)").foregroundColor(.white)) 	} }
2
0
2.4k
Apr ’21
Crash in swift_getObjectType or processDefaultActor when using (nested) async/await with URLSession
Hi, when using URL session nested in a few async/await calls I get a crash in swift_getObjectType (sometimes in processDefaultActor). Any ideas what could be causing this or hints how to debug/where to look? For a (contrived - because it was extracted from a larger project) example please see below (see "crashes here" comment for the last call before the crash). Thanks for any hints in advance! Cheers, Michael // Crash on: Xcode Version 13.0 beta (13A5155e), macOS 11.4 (20F71), on iPhone Simulator import CoreData import SwiftUI struct ContentView: View { @StateObject var dataCoordinator: DataCoordinator = .init() var body: some View { Button { print("GO") async { try await dataCoordinator.api.getSomething() } } label: { Label("Go", systemImage: "figure.walk") } .buttonStyle(.bordered) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext) } } // MARK: - Test coding - class DataCoordinator: ObservableObject { let api: API = .init() func refreshSomething() async throws { try await api.getSomething() } } // MARK: - class API { var session: URLSession = .init(configuration: .ephemeral) func getSomething() async throws { let url = URL(string: "https://www.heise.de")! let request = URLRequest(url: url) let (data, response) = try await _failsafe(request: request) print("\(response)") } private func _failsafe(request: URLRequest) async throws -> (Data, URLResponse) { do { var (data, response) = try await session.data(for: request) let httpResponse = response as! HTTPURLResponse var recovered = false if httpResponse.allHeaderFields["dsfsfsdsfds"] == nil { let login = LoginAsync() await login.login(session: session) recovered = true } if recovered { let req2 = URLRequest(url: URL(string: "https://www.heise.de")!) print("right before crash") try await session.data(for: req2) // crashes here with EXC_BAD_ACCESS print("right after crash ;-)") } return (data, response) } catch { print("\(error)") throw error } } } // MARK: - actor LoginAsync { func login(session: URLSession) async { let url = URL(string: "https://www.google.com")! let request = URLRequest(url: url) do { let (data, response) = try await session.data(for: request) } catch { print("\(error)") } } }
2
0
2.5k
Jul ’21
SwiftUI .fileImporter and custom UTType
Hi, I want to import GPX files into my iOS App. It works fine in the simulator using: .fileImporter(isPresented: $showFileImporter, allowedContentTypes: [UTType(filenameExtension: "gpx")!, UTType(filenameExtension: "GPX")!], allowsMultipleSelection: true) But running the app on an actual device (iOS 15 Beta 6), I am not allowed to select any of the GPX files. The strange thing is, that if I am using "jpg" instead of "gpx" I can select "jpg" files just fine. So it seems, that it has to do something with the "GPX" type being 'custom'. Any idea/hint what I am missing? Thank you! Michael
2
0
3.2k
Aug ’22
Selection state is lost when navigating to/from home screen
Hi! When using the Sample "NavigationCookbook" in the two column layout, the selection in the first column is not remembered, when navigating to the Home Screen and back. This behaviour can be reproduced by starting the app on the iPad or simulator, selecting for example "Pancake" and then navigating to the home screen and back into the navigation. Sometimes this (the navigation to/back from the home screen) has to be done twice, to lose the selection. In the console log you can see the message "Update NavigationAuthority bound path tried to update multiple times per frame." appearing. Not sure if this has something todo with the selection being lost. This is on iOS 16.4.1 not sure if the behaviour before was different. Anybody experiences the same behaviour? Bug in SwiftUI or in the sample app? Cheers, Michael
2
1
948
Apr ’23
Can't test equality of two model entities with a predicate
Hi, given this model: @Model class OnlyName { var name: String init(name: String) { self.name = name } } I would assume that I could write a predicate like this: #Predicate<OnlyName> { $0.name == other.name }, where other is also an instance of OnlyName for example returned by an earlier fetch. Unfortunately this results in the following compiler errors: Initializer 'init(_:)' requires that 'OnlyName' conform to 'Encodable' Initializer 'init(_:)' requires that 'OnlyName' conform to 'Decodable' Any idea if this is a bug in SwiftData or if I am missing something? Cheers, Michael
2
0
1.3k
Jun ’23
Can't query for the existence of an optional to-one relationship?
Hi, say in my model I have members and each member optionally can have a relationship to a Club. So the relationship in the Member entity would be modelled like so: @Relationship(.nullify, inverse: \Club.members) var club: Club? Now I would like to fetch al Members with no Club relationship. I would assume that this would work with a predicate like this: let noClubPred = #Predicate<Member> { member in member.club == nil } Unfortunately this gives me the following error when compiling: Generic parameter 'RHS' could not be inferred. Has anybody an idea how to phrase this predicate correctly, or is this a beta issue and it should actually work? Thank you! Cheers, Michael
2
1
1.3k
Sep ’23
Is SwiftData's #Unique currently broken or am I missing something?
Hi, I am inserting two models where the "unique" attribute is the same. I was under the impression, that this should result in an upsert and not two inserts of the model, but that is not the case. See the test coding below for what I am doing (it is self contained, so if you want to try it out, just copy it into a test target). The last #expect statement fails because of the two inserts. Not sure if this is a bug (Xcode 16 beta 2 on Sonoma running an iOS 18 simulator) or if I am missing something here... // MARK: - UniqueItem - @Model final class UniqueItem { #Unique<UniqueItem>([\.no]) var timestamp = Date() var title: String var changed = false var no: Int init(title: String, no: Int) { self.title = title self.no = no } } // MARK: - InsertTests - @Suite("Insert Tests", .serialized) struct InsertTests { var sharedModelContainer: ModelContainer = { let schema = Schema([ UniqueItem.self, ]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() @Test("Test unique.") @MainActor func upsertAndModify() async throws { let ctx = sharedModelContainer.mainContext try ctx.delete(model: UniqueItem.self) let item = UniqueItem(title: "Item \(1)", no: 0) ctx.insert(item) let allFD = FetchDescriptor<UniqueItem>() let count = try ctx.fetchCount(allFD) #expect(count == 1) let updatedItem = UniqueItem(title: "Item \(1)", no: 0) updatedItem.changed = true ctx.insert(updatedItem) // we should still have only 1 item because of the unique constraint let allCount = try ctx.fetchCount(allFD) #expect(allCount == 1) } }
2
2
1.1k
Sep ’24