iCloud & Data

RSS for tag

Learn how to integrate your app with iCloud and data frameworks for effective data storage

CloudKit Documentation

Posts under iCloud & Data subtopic

Post

Replies

Boosts

Views

Activity

Warning in Xcode console: Couldn't read values in CFPrefsPlistSource
I have enabled an App Group in my App and the Widget Extension. I use it to share my UserDefaults. Every time the app starts I now get the following error message in the Xcode console: Couldn't read values in CFPrefsPlistSource<0x303034510> (Domain: group.XX.XXXX.XXXX, User: kCFPreferencesAnyUser, ByHost: Yes, Container: (null), Contents Need Refresh: Yes): Using kCFPreferencesAnyUser with a container is only allowed for System Containers, detaching from cfprefsd The shared UserDefaults itself works without problems. Any ideas how I could get rid of this warning?
1
1
3.1k
Oct ’24
How to "Keep on My iPhone" after disabling iCloud for my app using Core Data
I have Core Data setup with a NSPersistentCloudKitContainer as my container, I've added a container identifier and I see my data on CloudKit's database here when I use "Act As iCloud Account". Here's what I have under capabilities in Xcode However, on my device when I go to Settings > Apple Account > iCloud > Saved to iCloud and switch off my app, all the data saved to Core Data is removed. I suspected this working as intended. When I switch it back on, all the data comes back. However (x2), the support page here says it should remain on the device: When you turn it off, the app no longer connects with iCloud, so your data exists only on your device Am I missing something in how I integrated Core Data in Xcode? Do I need to explicitly configure something with Apple's SDK to get the behavior described in the support page? I've noticed for some of Apple's apps, when you switch off iCloud there's an action sheet asking what you'd like to do with the local data. I figured this was Apple's magic without sharing especially since the buttons looked different Stocks Safari Contacts However (x3), not all apps that had this option offered "Keep on My iPhone", so perhaps the supported behavior is to remove what's on the device and these Apple apps implemented their own support to keep a copy on the device. Reminders I've tried testing some 3rd-party apps but couldn't convince myself they were using Core Data with iCloud enabled. Instead, it looked like they were using iCloud as a backup
1
1
951
Nov ’24
CloudKit it writes to development container, not Production
I have an app that I signed and distribute between some internal testflight users. Potentially I want to invite some 'Public' beta testers which don't need to validate (_World have read rights in the public database) Question: Do I need to have a working public CloudKit , when users are invited through TestFlight, or are they going to test on the development container? I understand that when I invite beta-tester without authorization (external testers) they cannot access the developer container, so therefore I need to have the production CloudKit container up and running. I have tried to populate the public production container, but for whatever reason my upload app still goes to the development container. I have archived the app, and tried, but no luck. I let xcode manage my certificates/profiles. but what do I need to change to be able to use my upload file to upload the production container, instead of the development. I tried: init() { container = CKContainer(identifier: "iCloud.com.xxxx.xxxx") publicDB = container.publicCloudDatabase I got no error in the console, but data is always populated to the development database, instead the production. I tried to create a provisioning profile, but for some reason Xcode doesn't like it. Tried to create one a different provisioning profile manual through the developer portal, for the app. but xcode doesn't want to use that, and mentions that the requirement are already in place. What can I check/do to solve this.
1
0
77
Aug ’25
Are data in an iCloud NSUbiquitousKeyValueStore directly available at app launch on another device?
Hello, I'm planning to had an onboarding to one of my apps. I am thinking about a way for a user to not see the onboarding again if he installs the app on another device. So for example, the user completes the onboarding on its iPhone, then downloads the app on its iPad and launch it, he doesn't see the onboarding a second time. I thought about using iCloud NSUbiquitousKeyValueStored to store the onboarding completion state. But I'm not sure when the data is synced to the other device logged into the same Apple account: Immediately even if the app is not installed on the other device (independent from the app, only iCloud thing)? At the same time as the app install on the other device? After the app is first launched on the other device? Of course synchronisation will depend on the Internet connection, speed, etc. so the app should handle the case where the data is not here but what would be the best case scenario? Thank you, Axel
1
0
52
Aug ’25
How to diagnose spurious SwiftDataMacros error
I have a Package.swift file that builds and runs from Xcode 15.2 without issue but fails to compile when built from the command line ("swift build"). The swift version is 6.0.3. I'm at wits end trying to diagnose this and would welcome any thoughts. The error in question is error: external macro implementation type 'SwiftDataMacros.PersistentModelMacro' could not be found for macro 'Model()'; plugin for module 'SwiftDataMacros' not found The code associated with the module is very vanilla. import Foundation import SwiftData @Model public final class MyObject { @Attribute(.unique) public var id:Int64 public var vertexID:Int64 public var updatedAt:Date public var codeUSRA:Int32 init(id:Int64, vertexID:Int64, updatedAt:Date, codeUSRA:Int32) { self.id = id self.vertexID = vertexID self.updatedAt = updatedAt self.codeUSRA = codeUSRA } public static func create(id:Int64, vertexID:Int64, updatedAt:Date, codeUSRA:Int32) -> MyObject { MyObject(id: id, vertexID: vertexID, updatedAt: updatedAt, codeUSRA: codeUSRA) } } Thank you.
1
1
302
Apr ’25
Core Data migration then run old app version
I'm sorta baffled right now. I am trying to wonder how I might detect a updated SQL Store in an older app. have a baseline app, and create a SQL-based repository in an updated app, change the model and verify that you can see the updated model version. Using lightweight migration re-run the older app (which will inherit the newer SQL repository). YIKES - no error when creating the NSPersistenStoreCoordinator! Nothing in the metadata to imply the store is newer than the model: [_persistentStoreCoordinator metadataForPersistentStore:store] My question: is there any way to detect this condition? David
1
0
670
Nov ’24
Develop a piece of code to force iCloud Drive sync
Hello, I apologize if this post could be slightly out of forum topic but I have one issue that I cannot solve. I tried a few times to call Apple support but the only indication that have given to me is to try with this forum. The issue I have is simple. Sometimes the modifications performed on iCloud Drive on one computer are not properly synced between the local folder /Users/[username]/Library/Mobile Documents/... and the cloud and therefore are not shared across all devices that use the same iCloud Drive. This is very disturbing as it may lead to a data loss. I would like to write a simple software that activates the iCloud Drive sync between the local iCloud folder /Users/[username]/Library/Mobile Documents/... and the Cloud. A simple macOS bash script would be fine but also other pieces of software are welcome. Can anyone please help me? Thanks! Daniele
1
0
725
Jan ’25
Disable SwiftData CloudKit sync when iCloud account is unavailable
I have a widely-used app that lets users keep track of personal data. This data is persisted with SwiftData, and synced with CloudKit. I understand that if the user's iCloud account changes on a device (for example, user logs out or toggles off an app's access to iCloud), then NSPersistentCloudKitContainer will erase the local data records on app launch. This is intentional behavior, intended as a privacy feature. However, we are receiving regular reports from users for whom the system has incorrectly indicated that the app's access to iCloud is unavailable, even when the user hasn't logged out or toggled off permission to access iCloud. This triggers the behavior to clear the local records, and even though the data is still available in iCloud, to the user, it looks like their data has disappeared for no reason. Helping the user find and troubleshoot their iCloud app data settings can be very difficult, since in many cases the user has no idea what iCloud is, and we can't link them directly to the correct settings screen. We seem to get these reports most frequently from users whose iCloud storage is full (which feels like punishment for not paying for additional storage), but we've also received reports from users who have enough storage space available (and are logged in and have the app's iCloud data permissions toggled on). It appears to happen randomly, as far as we can tell. I found a blog post from two years ago from another app developer who encountered the same issue: https://crunchybagel.com/nspersistentcloudkitcontainer/#:~:text=The%20problem%20we%20were%20experiencing To work around this and improve the user experience, we want to use CKContainer.accountStatus to check if the user has an available iCloud account, and if not, disable the CloudKit sync before it erases the local data. I've found steps to accomplish this workaround using CoreData, but I'm not sure how to best modify the ModelContainer's configuration after receiving the CKAccountStatus when using SwiftData. I've put together this approach so far; is this the right way to handle disabling/enabling sync based on account status? import SwiftUI import SwiftData import CloudKit @main struct AccountStatusTestApp: App { @State private var modelContainer: ModelContainer? var body: some Scene { WindowGroup { if let modelContainer { ContentView() .modelContainer(modelContainer) } else { ProgressView("Loading...") .task { await initializeModelContainer() } } } } func initializeModelContainer() async { let schema = Schema([ Item.self, ]) do { let accountStatus = try await CKContainer.default().accountStatus() let modelConfiguration = ModelConfiguration( schema: schema, cloudKitDatabase: accountStatus == .available ? .private("iCloud.com.AccountStatusTestApp") : .none ) do { let container = try ModelContainer(for: schema, configurations: [modelConfiguration]) modelContainer = container } catch { print("Could not create ModelContainer: \(error)") } } catch { print("Could not determine iCloud account status: \(error)") } } } I understand that bypassing the clearing of local data when the iCloud account is "unavailable" introduces possible issues with data being mingled on shared devices, but I plan to mitigate that with warning messages when users are in this state. This would be a far more preferable user experience than what's happening now.
1
0
1k
Jan ’25
QuotaExceeded error for RecordDelete operation
In the CloudKit logs I see logs that suggest users getting QUOTA_EXCEEDED error for RecordDelete operations. { "time":"21/07/2025, 7:57:46 UTC" "database":"PRIVATE" "zone":"***" "userId":"***" "operationId":"***" "operationGroupName":"2.3.3(185)" "operationType":"RecordDelete" "platform":"iPhone" "clientOS":"iOS;18.5" "overallStatus":"USER_ERROR" "error":"QUOTA_EXCEEDED" "requestId":"***" "executionTimeMs":"177" "interfaceType":"NATIVE" "recordInsertBytes":54352 "recordInsertCount":40 "returnedRecordTypes":"_pcs_data" } I'm confused as to what this means? Why would a RecordDelete operation have recordInsertBytes? I'd expect a RecordDelete operation to never fail on quotaExceeded and how would I handle that in the app?
1
0
61
Jul ’25
SwiftData thread-safety: passing models between threads
Hello, I'm trying to understand how dangerous it is to read and/or update model properties from a thread different than the one that instantiated the model. I know this is wrong when using Core Data and we should always use perform/performAndWait before manipulating an object but I haven't found any information about that for SwiftData. Question: is it safe to pass an object from one thread (like MainActor) to another thread (in a detached Task for example) and manipulate it, or should we re fetch the object using its persistentModelID as soon as we cross threads? When running the example app below with the -com.apple.CoreData.ConcurrencyDebug 1 argument passed at launch enabled, I don't get any Console warning when I tap on the "Update directly" button. I'm sure it would trigger a warning if I were using Core Data. Thanks in advance for explaining. Axel -- @main struct SwiftDataPlaygroundApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: Item.self) } } } struct ContentView: View { @Environment(\.modelContext) private var context @Query private var items: [Item] var body: some View { VStack { Button("Add") { context.insert(Item(timestamp: Date.now)) } if let firstItem = items.first { Button("Update directly") { Task.detached { // Not the main thread, but firstItem is from the main thread // No warning in Xcode firstItem.timestamp = Date.now } } Button("Update using persistentModelID") { let container: ModelContainer = context.container let itemIdentifier: Item.ID = firstItem.persistentModelID Task.detached { let backgroundContext: ModelContext = ModelContext(container) guard let itemInBackgroundThread: Item = backgroundContext.model(for: itemIdentifier) as? Item else { return } // Item on a background thread itemInBackgroundThread.timestamp = Date.now try? backgroundContext.save() } } } } } } @Model final class Item: Identifiable { var timestamp: Date init(timestamp: Date) { self.timestamp = timestamp } }
1
1
743
Oct ’24
Troubleshooting CloudKit JS iCloud Backup: setupAuth() Returns Null After Sign in with Apple
Hi, I'm implementing iCloud backup functionality in my web application using CloudKit JS, but I'm running into some issues. I'd appreciate any help you can provide. Issue: The iCloud backup feature isn't working properly in our web app. I believe I've correctly set up the Apple Developer Program registration and API token generation. While a demo implementation works perfectly with iCloud backup, our app implementation is failing. Specifically: "Sign in with Apple" succeeds However, ck.getDefaultContainer().setupAuth() returns null In the working demo, setupAuth() returns a proper value Even after logging in through the redirect URL provided in the "421 Misdirected Request" error response and executing setupAuth(), it still returns null I've essentially copied the working demo code directly, so I suspect the issue might be related to token generation, permissions, or account configuration. Questions: Could you provide detailed step-by-step instructions for implementing iCloud backup in a web application? I've noticed there are configuration items in the Developer Console and Certificates console, so I may have missed something in one of these areas. Based on the symptoms described, what are the possible causes for setupAuth() returning null in CloudKit JS? Could configuration issues be indirectly causing this, or is it more likely a timing issue or SDK coding problem? Specifically regarding the 421 error and redirect flow - is there something in the configuration that could cause setupAuth() to return null even after successful authentication through the redirect? Thanks in advance for your help!
1
0
63
Jul ’25
How to get a real time and date (not device time) for query?
I need to know the current date to query CloudKit data with it, like: let predicate = NSPredicate(format: "publishedAt <= %@", currentDateAndTime) I don't need high precision, even +/- a few minutes is fine, but I can't rely on device's time since the user can manually change it. Researching this myself I see that the most reliable method is to get the date from the server. There are NTP servers, but accessing them requires additional libraries which adds complexity. TrueTime (last updated 6 years ago) and Kronos (updated like once a year) seem outdated, given how much Swift has changed in the past years. I can make an HTTP request to a website like Google or Apple and read the current time from its headers. But I don't know if this method is reliable. I know I can create a dummy record in CloudKit, update it, and read its modificationDate. But it feels hacky. Maybe there is another way to fetch the current date directly from CloudKit? It feels like it should be easy and there is a straightforward solution, but I just can't find it.
1
0
582
Jan ’25
How can the owner access a zone he shared on cloudkit?
Using this Apple repository as a basis https://github.com/apple/sample-cloudkit-zonesharing I created and verified the shared zone and the same zone is private for the person who shared it and shared for the person who received it, so aren't they the same zones? [same zone but different id?] I can make the person who shared the zone (owner) access the zone as a .shared scope just like the person who was shared.
1
0
481
Oct ’24
CrashReportError: Fatal Error in PersistentModel.swift
I got a preview crash info as this: *** crashed due to fatalError in PersistentModel.swift at line 559. This KeyPath does not appear to relate RecordInfo to anything - \RecordInfo.<computed 0x00000001921dfb4e (Array<SomeInfo>)> If I change preview device to iPhoneSE, It is no crash. I think the reason is I have some dirty data in iPhone16 Pro preview device. If I'm right and how to delete it? Model of RecordInfo like this: @Model class RecordInfo { @Relationship(deleteRule: .cascade) var someInfo:[SomeInfo] } @Model class SomeInfo { var date: Date var info: String }
1
0
505
Nov ’24
SwiftData + CloudKit causes watchOS app termination during WKExtendedRuntimeSession (FB17685611)
Hi all, I’m encountering a consistent issue with SwiftData on watchOS when using CloudKit sync. After enabling: let config = ModelConfiguration(schema: schema, cloudKitDatabase: .automatic) …the app terminates ~30–60 seconds into a WKExtendedRuntimeSession. This happens specifically when: Always-On Display is OFF The iPhone is disconnected or in Airplane Mode The app is running in a WKExtendedRuntimeSession (e.g., used for meditation tracking) The Xcode logs show a warning: Background Task ("CoreData: CloudKit Setup"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. It appears CloudKit sync setup is being triggered automatically and flagged by the system as an unmanaged long-running task, leading to termination. Workaround: Switching to: let config = ModelConfiguration(schema: schema, cloudKitDatabase: .none) …prevents the issue entirely — no background task warning, no crash. Feedback ID submitted: FB17685611 Just wanted to check if others have seen this behavior or found alternative solutions. It seems like something Apple may need to address in SwiftData’s CloudKit handling on watchOS.
1
1
158
May ’25
SwiftData Relationship Delete Not Working (SwiftData/PersistentModel.swift:359)
SwiftData delete isn't working, when I attempt to delete a model, my app crashes and I get the following error: SwiftData/PersistentModel.swift:359: Fatal error: Cannot remove My_App.Model2 from relationship Relationship - name: model2, options: [], valueType: Model2, destination: Model2, inverseName: models3, inverseKeypath: Optional(\Model2.models3) on My_App.Model3 because an appropriate default value is not configured. I get that it's saying I don't have a default value, but why do I need one? Isn't @Relationship .cascade automatically deleting the associated models? And onto of that, why is the error occurring within the do block, shouldn't it be caught by the catch, and printed? I have put together a sample project below. import SwiftUI import SwiftData @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: Model3.self) } } } @Model class Model1 { var name: String @Relationship(deleteRule: .cascade, inverse: \Model2.model1) var models2: [Model2] = [] init(name: String) { self.name = name } } @Model class Model2 { var name: String var model1: Model1 @Relationship(deleteRule: .cascade, inverse: \Model3.model2) var models3: [Model3] = [] init(name: String, model1: Model1) { self.name = name self.model1 = model1 } } @Model class Model3 { var name: String var model2: Model2 init(name: String, model2: Model2) { self.name = name self.model2 = model2 } } struct ContentView: View { @Query var models1: [Model1] @Environment(\.modelContext) var modelContext var body: some View { NavigationStack { List(models1) { model1 in Text(model1.name) .swipeActions { Button("Delete", systemImage: "trash", role: .destructive) { modelContext.delete(model1) do { try modelContext.save() //SwiftData/PersistentModel.swift:359: Fatal error: Cannot remove My_App.Model2 from relationship Relationship - name: model2, options: [], valueType: Model2, destination: Model2, inverseName: models3, inverseKeypath: Optional(\Model2.models3) on My_App.Model3 because an appropriate default value is not configured. } catch { print(error.localizedDescription) } } } } .toolbar { Button("Insert", systemImage: "plus") { modelContext.insert(Model3(name: "model3", model2: Model2(name: "model2", model1: Model1(name: "model1")))) } } } } }
1
0
1k
Jan ’25
File Provider Extension trouble
Hi everyone, I am a beginner in iOS/Swift programming. I'm trying to develop a mobile application that allows to mount a network drive in the iphone Files application via the WebDav protocol. I saw on the internet that WebDav is no longer implemented in iOS because considered deprecated by apple. To accomplish this task, I decided to separate responsibilities as follows: Framework: WebDav (responsible for communication with the WebDav server) FileProviderExtension: FileBridge (Responsible for bridging the gap between the WebDav Framework and the iOS Files app) Main App I also have an AppGroup that includes the main application and the fileproviderextension Initially, to measure the feasibility and complexity of this task, I'd like to make a simplistic version that simply displays the files on my drive in the Files app, without necessarily being able to interact with them. FileProviderExtension.swift: import FileProvider import WebDav class FileProviderExtension: NSObject, NSFileProviderReplicatedExtension { private var webDavService: WebDavService? required init(domain: NSFileProviderDomain) { super.init() self.webDavService = WebDavService(baseURL: URL(string: "https://www.mydrive.com/drive")!) } func invalidate() { // TODO: cleanup any resources } func item(for identifier: NSFileProviderItemIdentifier, request: NSFileProviderRequest, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) -> Progress { let progress = Progress(totalUnitCount: 1) Task { do { if let items = try await webDavService?.propfind(path: identifier.rawValue, depth: 1), let item = items.first(where: { $0.itemIdentifier == identifier }) { completionHandler(item, nil) } else { completionHandler(nil, NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: nil)) } } catch { completionHandler(nil, error) } } return progress } func fetchContents(for itemIdentifier: NSFileProviderItemIdentifier, version requestedVersion: NSFileProviderItemVersion?, request: NSFileProviderRequest, completionHandler: @escaping (URL?, NSFileProviderItem?, Error?) -> Void) -> Progress { let progress = Progress(totalUnitCount: 1) Task { do { guard let service = webDavService else { throw WebDavError.invalidResponse } let data = try await service.get(fileAt: itemIdentifier.rawValue) let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent(itemIdentifier.rawValue) try data.write(to: tempURL) completionHandler(tempURL, nil, nil) } catch { completionHandler(nil, nil, error) } } return progress } func createItem(basedOn itemTemplate: NSFileProviderItem, fields: NSFileProviderItemFields, contents url: URL?, options: NSFileProviderCreateItemOptions = [], request: NSFileProviderRequest, completionHandler: @escaping (NSFileProviderItem?, NSFileProviderItemFields, Bool, Error?) -> Void) -> Progress { // TODO: a new item was created on disk, process the item's creation completionHandler(itemTemplate, [], false, nil) return Progress() } func modifyItem(_ item: NSFileProviderItem, baseVersion version: NSFileProviderItemVersion, changedFields: NSFileProviderItemFields, contents newContents: URL?, options: NSFileProviderModifyItemOptions = [], request: NSFileProviderRequest, completionHandler: @escaping (NSFileProviderItem?, NSFileProviderItemFields, Bool, Error?) -> Void) -> Progress { // TODO: an item was modified on disk, process the item's modification completionHandler(nil, [], false, NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError, userInfo:[:])) return Progress() } func deleteItem(identifier: NSFileProviderItemIdentifier, baseVersion version: NSFileProviderItemVersion, options: NSFileProviderDeleteItemOptions = [], request: NSFileProviderRequest, completionHandler: @escaping (Error?) -> Void) -> Progress { // TODO: an item was deleted on disk, process the item's deletion completionHandler(NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError, userInfo:[:])) return Progress() } func enumerator(for containerItemIdentifier: NSFileProviderItemIdentifier, request: NSFileProviderRequest) throws -> NSFileProviderEnumerator { return FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier, service: webDavService) } } Here's the code I use to initialize my domain in the main app files: fileprivate func registerFileProviderDomain() { let domainIdentifier = NSFileProviderDomainIdentifier("FileProviderExtension Bundle Identifier") let domain = NSFileProviderDomain(identifier: domainIdentifier, displayName: "My Drive") NSFileProviderManager.add(domain) { error in NSFileProviderManager.add(domain) { error in if let error = error { print("Error cannot add domain file provider : \(error.localizedDescription)") } else { print("Success domain file provider added") } } } I can't get rid of the Error : Error cannot add domain file provider : The operation couldn’t be completed. Invalid argument. I don't know what I'm missing Please help me understand
1
1
962
Jan ’25
Swift Data issue with a recursive model class
Dear Apple Developer Forum As the title suggests, I have an issue with Swift Data when I want to modify a property of a recursive model class instance. Please consider the following sample project: import SwiftUI import SwiftData @main struct ISSUEApp: App { var sharedModelContainer: ModelContainer = { let schema = Schema([ Item.self, ]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() var body: some Scene { WindowGroup { ContentView() } .modelContainer(sharedModelContainer) } } @Model final class Item { var name: String? var parent: Item? init(name: String?, parent: Item?) { self.name = name self.parent = parent } } struct ContentView: View { @Environment(\.modelContext) private var context @Query private var items: [Item] @State private var itemToMove: Item? @State private var count: Int = 0 @State private var presentMoveView: Bool = false var body: some View { NavigationStack() { List(items, id: \.id) {item in Button(action: { itemToMove = item }, label: { Text("Id: \(item.name ?? "ERROR") and my parent iD is \(item.parent?.name ?? "root")") .bold(itemToMove == item) .italic(itemToMove == item) }) } .sheet(isPresented: $presentMoveView, content: { MoveView(toMove: self.itemToMove!) }) .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button(action: { let i = Item(name: "\(count)", parent: nil) context.insert(i) try? context.save() count += 1 }, label: { Text("Add an item") }) } ToolbarItem(placement: .navigationBarLeading) { Button(action: { presentMoveView.toggle() }, label: { Text("Move selected item") }) } } } } } struct MoveView: View { @Environment(\.modelContext) private var modelContext @Environment(\.dismiss) private var dismiss @Query private var items: [Item] @Bindable var toMove: Item @State private var selectedFutureParent: Item? var body: some View { NavigationStack(){ List(items, id: \.id) {item in Button(action: { selectedFutureParent = item }, label: { Text("Id: \(item.name ?? "ERROR") and my parent iD is \(item.parent?.name ?? "root")") .bold(selectedFutureParent == item) .italic(selectedFutureParent == item) }) } .toolbar(){ ToolbarItem{ Button("Move", action: { toMove.parent = selectedFutureParent dismiss() }) } } } } } #Preview { ContentView() .modelContainer(for: Item.self, inMemory: true) } Please launch the preview of this app, add items (as many as you'd like), select one and click on the "Move selected item" button. Select the new parent of the item. As you may have noticed, both selected items (moved item and new parent) are modified, whereas only one equality is used. This issue seems to be independent from the @Bindable property wrapper. I tried many things, such as using index instead of direct elements; using local let constant for the parent but the constant is still modified (very weird...) Thank you in advance for your help ! Best regards
1
0
974
Oct ’24