I'm developing an app that uses CloudKit synchronization with SwiftData and on visionOS I added an App Settings bundle. I have noticed that sometimes, when the app is open and the user changes a setting from the App Settings bundle, the following fatal error occurs:
SwiftData/BackingData.swift:831: Fatal error: This model instance was destroyed by calling ModelContext.reset and is no longer usable.
The setting is read within the App struct in the visionOS app target using @AppStorage and this value is in turn used to set the passthrough video dimming via the .preferredSurroundingsEffect modifier. The setting allows the user to specify the dimming level as dark, semi dark, or ultra dark.
The fatal error appears to occur intermittently although the first time it was observed was after adding the settings bundle. As such, I suspect there is some connection between those code changes and this fatal error even though they do not directly relate to SwiftData.
                    
                  
                iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
  
    
    Selecting any option will automatically load the page
  
  
  
  
    
  
  
            Post
Replies
Boosts
Views
Activity
                    
                      Hi,
I’m running into an issue with Core Data migrations using a custom NSMappingModel created entirely in Swift (not using .xcmappingmodel files).
Setup:
•	I’m performing a migration with a manually constructed NSMappingModel
•	One of the NSEntityMapping instances is configured as follows:
•	mappingType = .customEntityMappingType (or .transformEntityMappingType)
•	entityMigrationPolicyClassName is set to a valid subclass of NSEntityMigrationPolicy
•	The class implements the expected methods like:
@objc func createDestinationInstances(…) throws { … }
@objc func createCustomDestinationInstance(…) throws -> NSManagedObject { … }
The policy class is instantiated (confirmed via logging in init()),
but none of the migration methods are ever called.
I have also tried adding valid NSPropertyMapping instances with real valueExpression bindings to force activation, but that didn’t make a difference.
Constraints:
•	I cannot use .xcmappingmodel files in this context due to transformable attributes not compatible with the visual editor.
•	Therefore, I need the entire mapping model to be defined in Swift.
Workaround:
As a temporary workaround, I’m migrating the data manually using two persistent stores and NSManagedObjectContext, but I’d prefer to rely on NSMigrationManager as designed.
Question:
Is there a known limitation that prevents Core Data from invoking NSMigrationPolicy methods when using in-memory NSMappingModel instances?
Or is there any specific setup required to trigger them when not loading from .xcmappingmodel?
Thanks in advance.
                    
                  
                
                    
                      I have been working on an app for the past few months, and one issue that I have encountered a few times is an error where quick subsequent deletions cause issues with detached tasks that are triggered from some user actions.
Inside a Task.detached, I am building an isolated model context, querying for LineItems, then iterating over those items. The crash happens when accessing a Transaction property through a relationship.
var byTransactionId: [UUID: [LineItem]] {
    return Dictionary(grouping: self) { item in
        item.transaction?.id ?? UUID()
    }
}
In this case, the transaction has been deleted, but the relationship existed when the fetch occurred, so the transaction value is non-nil. The crash occurs when accessing the id. This is the error.
SwiftData/BackingData.swift:1035: Fatal error: This model instance was invalidated because its backing data could no longer be found the store. PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(backing: SwiftData.PersistentIdentifier.PersistentIdentifierBacking.managedObjectID(0xb43fea2c4bc3b3f5 <x-coredata://A9EFB8E3-CB47-48B2-A7C4-6EEA25D27E2E/Transaction/p1756>)))
I see other posts about this error and am exploring some suggestions, but if anyone has any thoughts, they would be appreciated.
                    
                  
                
                    
                      How does SwiftData work with background operations? CoreData had background context that could be used to avoid UI hang for heavy operations.
Is there an equivalent in SwiftData, and if so, do I have to merge changes or does it save directly to persistent store?
                    
                  
                
                    
                      Hi all,
As you know, when using SwiftData Cloudkit, all relationships are required to be optional.
In my app, which is a list app, I have a model class Project that contains an array of Subproject model objects. A  Subproject also contains an array of another type of model class and this chain goes on and on.
In this type of pattern, it becomes really taxxing to handle the optionals the correct way, i.e. unwrap them as late as possible and display an error to the user if unable to.
It seems like most developers don't even bother, they just wrap the array in a computed property that returns an empty array if nil.
I'm just wondering what is the recommended way by Apple to handle these optionals. I'm not really familiar with how the CloudKit backend works, but if you have a simple list app that only saves to the users private iCloud, can I just handwave the optionals like so many do? Is it only big data apps that need to worry? Or should we always strive to handle them the correct way? If that's the case, why does it seem like most people  skip over them? Be great if an Apple engineer could weigh in.
                    
                  
                
                    
                      Every time I insert a subclass (MYShapeLayer) into the model context, the app crashes with an error:
DesignerPlayground crashed due to fatalError in BackingData.swift at line 908. Never access a full future backing data - PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(backing: SwiftData.PersistentIdentifier.PersistentIdentifierBacking.managedObjectID(0xb2dbc55f3f4c57f2 <x-coredata://B1E3206B-40DE-4185-BC65-4540B4705B40/MYShapeLayer/p1>))) with Optional(A6CA4F89-107F-4A66-BC49-DD7DAC689F77)
struct ContentView: View {
  
  @Environment(\.modelContext) private var modelContext
  
  @Query private var designs: [MYDesign]
  
  var layers: [MYLayer] {
    designs.first?.layers ?? []
  }
  
  var body: some View {
    NavigationStack {
      List {
        ForEach(layers) { layer in
          Text(layer.description)
        }
      }
      .onAppear {
        let design = MYDesign(title: "My Design")
        modelContext.insert(design)
        try? modelContext.save()
      }
      .toolbar {
        Menu("Add", systemImage: "plus") {
          Button(action: addTextLayer) {
            Text("Add Text Layer")
          }
          
          Button(action: addShapeLayer) {
            Text("Add Shape Layer")
          }
        }
      }
    }
  }
   
  private func addTextLayer() {
    if let design = designs.first {
      let newLayer = MYLayer(order: layers.count, kind: .text)
      newLayer.design = design
      modelContext.insert(newLayer)
      try? modelContext.save()
    }
  }
  
  private func addShapeLayer() {
    if let design = designs.first {
      let newLayer = MYShapeLayer(shapeName: "Ellipse", order: layers.count)
      newLayer.design = design
      modelContext.insert(newLayer)
      try? modelContext.save()
    }
  }
}
#Preview {
  ContentView()
    .modelContainer(for: [MYDesign.self, MYLayer.self, MYShapeLayer.self], inMemory: true)
}
@Model
final class MYDesign {
  
  var title: String = ""
  
  @Relationship(deleteRule: .cascade, inverse: \MYLayer.design)
  var layers: [MYLayer] = []
  
  init(title: String = "") {
    self.title = title
  }
  
}
@available(iOS 26.0, macOS 26.0, *)
@Model
class MYLayer {
  
  var design: MYDesign!
  
  var order: Int = 0
  
  var title: String = ""
  
  init(order: Int = 0, title: String = "New Layer") {
    self.order = order
    self.title = title
  }
  
}
@available(iOS 26.0, macOS 26.0, *)
@Model
class MYShapeLayer: MYLayer {
  
  var shapeName: String = ""
  
  init(shapeName: String, order: Int = 0) {
    self.shapeName = shapeName
    super.init(order: order)
  }
}
                    
                  
                
                    
                      Hi everyone,
I’ve been working on migrating my app (SwimTimes, which helps swimmers track their times) to use Core Data + CKSyncEngine with Swift 6.
After many iterations, forum searches, and experimentation, I’ve created a focused sample project that demonstrates the architecture I’m using.
The good news:
👉 I believe the crashes I was experiencing are now solved, and the sync behavior is working correctly.
👉 The demo project compiles and runs cleanly with Swift 6.
However, before adopting this as the final architecture, I’d like to ask the community (and hopefully Apple engineers) to validate a few critical points, especially regarding Swift 6 concurrency and Core Data contexts.
Architecture Overview
Persistence layer: Persistence.swift sets up the Core Data stack with a main viewContext and a background context for CKSyncEngine.
Repositories: All Core Data access is abstracted into repository classes (UsersRepository, SwimTimesRepository), with async/await methods.
SyncEngine: Wraps CKSyncEngine, handles system fields, sync tokens, and bridging between Core Data entities and CloudKit records.
ViewModels: Marked @MainActor, exposing @Published arrays for SwiftUI. They never touch Core Data directly, only via repositories.
UI: Simple SwiftUI views bound to the ViewModels.
Entities:
UserEntity → represents swimmers.
SwimTimeEntity → times linked to a user (1-to-many).
Current Status
The project works and syncs across devices. But there are two open concerns I’d like validated:
Concurrency & Memory Safety
Am I correctly separating viewContext (main/UI) vs. background context (used by CKSyncEngine)?
Could there still be hidden risks of race conditions or memory crashes that I’m not catching?
Swift 6 Sendable Compliance
Currently, I still need @unchecked Sendable in the SyncEngine and repository layers.
What is the recommended way to fully remove these workarounds and make the code safe under Swift 6’s stricter concurrency rules?
Request
Please review this sample project and confirm whether the concurrency model is correct.
Suggest how I can remove the @unchecked Sendable annotations safely.
Any additional code improvements or best practices would also be very welcome — the intention is to share this as a community resource.
I believe once finalized, this could serve as a good reference demo for Core Data + CKSyncEngine + Swift 6, helping others migrate safely.
Environment
iOS 18.5
Xcode 16.4
macOS 15.6
Swift 6
Sample Project
Here is the full sample project on GitHub:
👉 [https://github.com/jarnaez728/coredata-cksyncengine-swift6]
Thanks a lot for your time and for any insights!
Best regards,
Javier Arnáez de Pedro
                    
                  
                
                    
                      I have  a simple app that makes an HTTPS call to gather some JSON which I then parse and add to my SwiftData database. The app then uses a simple @Query in a view to get the data into a list.
on iOS 16 this works fine. No problems. But the same code on iOS 26 (targeting iOS 18.5) crashes after about 15 seconds of idle time after the list is populated. The error message is:
Could not cast value of type '__NSCFNumber' (0x1f31ee568) to 'NSString' (0x1f31ec718).
and occurs when trying to access ANY property of the list.
I have a stripped down version of the app that shows the crash available.
To replicate the issue:
open the project in Xcode 26
target any iOS 26 device or simulator
compile and run the project.
after the list is displayed, wait about 15 seconds and the app crashes.
It is also of note that if you try to run the app again, it will crash immediately, unless you delete the app from the device.
Any help on this would be appreciated.
Feedback number FB20295815 includes .zip file
Below is the basic code (without the data models)
The Best Seller List.Swift
import SwiftUI
import SwiftData
@main
struct Best_Seller_ListApp: App {
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer (for: NYTOverviewResponse.self)
    }
}
ContentView.Swift
import os.log
import SwiftUI
struct ContentView: View {
    @Environment(\.modelContext) var modelContext
    
    @State private var listEncodedName = String()
    
    
    var body: some View {
        NavigationStack () {
            ListsView()
        }
        
        .task {
            await getBestSellerLists()
        }
    }
    
    func getBestSellerLists() async {
        guard let url = URL(string: "https://api.nytimes.com/svc/books/v3/lists/overview.json?api-key=\(NYT_API_KEY)") else {
            Logger.errorLog.error("Invalid URL")
            return
        }
        do {
            let decoder = JSONDecoder()
            var decodedResponse = NYTOverviewResponse()
            
            //decode the JSON
            let (data, _) = try await URLSession.shared.data(from: url)
            decoder.keyDecodingStrategy = .convertFromSnakeCase
            decodedResponse = try decoder.decode(NYTOverviewResponse.self, from: data)
            
            //remove any lists that don't have list_name_encoded. Fixes a bug in the data
            decodedResponse.results!.lists = decodedResponse.results!.lists!.filter { $0.listNameEncoded !=  "" }
            
            // sort the lists
            decodedResponse.results!.lists!.sort { (lhs, rhs) -> Bool in
                lhs.displayName < rhs.displayName
            }
            //delete any potential existing data
            try modelContext.delete(model: NYTOverviewResponse.self)
            
            //add the new data
            modelContext.insert(decodedResponse)
             
        } catch {
            Logger.errorLog.error("\(error.localizedDescription)")
        }
    }
}
ListsView.Swift
import os.log
import SwiftData
import SwiftUI
@MainActor
struct ListsView: View {
    //MARK: - Variables and Constants
    
    @Query var nytOverviewResponses: [NYTOverviewResponse]
    
    enum Updated: String {
        case weekly = "WEEKLY"
        case monthly = "MONTHLY"
    }
    
    //MARK: - Main View
    var body: some View {
        List {
            if nytOverviewResponses.isEmpty {
                ContentUnavailableView("No lists yet", systemImage: "list.bullet", description: Text("NYT Bestseller lists not downloaded yet"))
            } else {
                WeeklySection
                MonthlySection
            }
        }
        .navigationBarTitle("Bestseller Lists", displayMode: .large)
        .listStyle(.grouped)
    }
    
    
    var WeeklySection: some View {
        let rawLists = nytOverviewResponses.last?.results?.lists ?? []
        // Build a value-typed array to avoid SwiftData faulting during sort
        let weekly = rawLists
            .filter { $0.updateFrequency == Updated.weekly.rawValue }
            .map { (name: $0.displayName, encoded: $0.listNameEncoded, model: $0) }
            .sorted { $0.name < $1.name }
        
        return Section(header: Text("Weekly lists to be published on \(nytOverviewResponses.last?.results?.publishedDate ?? "-")")) {
            ForEach(weekly, id: \.encoded) { item in
                Text(item.name).font(Font.custom("Georgia", size: 17))
            }
        }
    }
    
    
    var MonthlySection: some View {
        let rawLists = nytOverviewResponses.last?.results?.lists ?? []
        // Build a value-typed array to avoid SwiftData faulting during sort
        let monthly = rawLists
            .filter { $0.updateFrequency == Updated.monthly.rawValue }
            .map { (name: $0.displayName, encoded: $0.listNameEncoded, model: $0) }
            .sorted { $0.name < $1.name }
        
        return Section(header: Text("Monthly lists to be published on \(nytOverviewResponses.last?.results?.publishedDate ?? "-")")) {
            ForEach(monthly, id: \.encoded) { item in
                Text(item.name).font(Font.custom("Georgia", size: 17))
            }
        }
    }
    
}
                    
                  
                
                    
                      I am working on a SwiftUI project using Core Data. I have an entity called AppleUser in my data model, with the following attributes: id (UUID), name (String), email (String), password (String), and createdAt (Date). All attributes are non-optional.
I created the corresponding Core Data class files (AppleUser+CoreDataClass.swift and AppleUser+CoreDataProperties.swift) using Xcode’s automatic generation. I also have a PersistenceController that initializes the NSPersistentContainer with the model name JobLinkModel.
When I try to save a new AppleUser object using:
let user = AppleUser(context: viewContext)
user.id = UUID()
user.name = "User1"
user.email = "..."
user.password = "password1"
user.createdAt = Date()【The email is correctly formatted, but it has been replaced with “…” for privacy reasons】
try? viewContext.save()
I get the following error in the console:Core Data save failed: Foundation._GenericObjCError.nilError, [:]
User snapshot: ["id": ..., "name": "User1", "email": "...", "password": "...", "createdAt": ...]
All fields have valid values, and the Core Data model seems correct. I have also tried:
•	Checking that the model name in NSPersistentContainer(name:) matches the .xcdatamodeld file (JobLinkModel)
•	Ensuring the AppleUser entity Class, Module, and Codegen are correctly set (Class Definition, Current Product Module)
•	Deleting duplicate or old AppleUser class files
•	Cleaning Xcode build folder and deleting the app from the simulator
•	Using @Environment(.managedObjectContext) for the context
Despite all this, I still get _GenericObjCError.nilError when saving a new AppleUser object.
I want to understand:
1.	Why is Core Data failing to save even though all fields are non-nil and correctly assigned?
2.	Could this be caused by some residual old class files, or is there something else in the setup that I am missing?
3.	What steps should I take to ensure that Core Data properly recognizes the AppleUser entity and allows saving?
Any help or guidance would be greatly appreciated.
                    
                  
                
                    
                      Hi, thank you for your reply. I have checked and confirmed that all AppleUser entity fields (id, name, email, password, createdAt) are optional, relationships (posts, comments) are optional, and I assign values when creating a new object, but Core Data still throws a nilError during registration; I have uploaded my project to GitHub for your reference here: https://github.com/Kawiichao/job. If reviewing it requires any payment, please let me know in advance. Thank you very much for your kind offer—I really appreciate it!
                    
                  
                
              
                
              
              
                
                Topic:
                  
	
		App & System Services
  	
                
                
                SubTopic:
                  
                    
	
		iCloud & Data
		
  	
                  
                
              
              
              
  
  
    
    
  
  
              
                
                
              
            
          
                    
                      The 'unique' attribute is a really nice feature, BUT. In some of my apps, the unique identifier for an object is a combination of multiple attributes. (Example: a book title is not unique, but a combination of book title and author list is.)
How do I model this with SwiftData? I cannot use @Attribute(.unique) on either the title OR the author list, but I want SwiftData to provide the same "insert or update" logic.
Is this possible?
                    
                  
                
                    
                      Hi All,
I  work on a cross platform app, iOS/macOS.
All devises on iOS could synchronize data from Coredata : I create a client, I see him an all iOS devices.
But when I test on macOs (with TestFlight) the Mac app could not get any information from iOs devices.
On Mac,  cloud drive is working because I could download and upload documents and share it between all devices, so the account is working but with my App on MacOS, there is no synchronisation.
idea????
                    
                  
                
                    
                      I have a simple app that uses SwiftUI and SwiftData to maintain a database. The app runs on multiple iPhones and iPads and correctly synchronises across those platforms. So I am correct setting Background Modes and Remote Notifications. I have also correctly setup my Model Configuration and ModelContainer (Otherwise I would expect syncing to fail completely).
The problem arises when I run on a Mac (M1 or M3) either using Mac Designed for iPad or Mac Catalyst. This can be debugging in Xcode or running the built app. Then the app does not reflect changes made in the iPhone or iPad apps unless I follow a specific sequence. Leave the app, (e.g click on a Finder window), then come back to the app (i.e click on the app again). Now the app will show the changes made on the iPhone/iPad.
It looks like the app on the Mac is not processing remote notifications when in the background - it only performs them when the app has just become active. It also looks like the Mac is not performing these sync operations when the app is active. I have tried waiting 30 minutes and still the sync doesn't happen unless I leave the app and come back to it.
I am using the same development CloudKit container in all cases
                    
                  
                
              
                
              
              
                
                Topic:
                  
	
		App & System Services
  	
                
                
                SubTopic:
                  
                    
	
		iCloud & Data
		
  	
                  
                
              
              
              
  
  
    
    
  
  
              
                
                
              
            
          
                    
                      我正在使用 Core Data 开发一个 SwiftUI 项目。我的数据模型中有一个名为 AppleUser 的实体,具有以下属性:id (UUID)、name (String)、email (String)、password (String) 和 createdAt (Date)。所有属性都是非可选的。
我使用 Xcode 的自动生成创建了相应的 Core Data 类文件(AppleUser+CoreDataClass.swift 和 AppleUser+CoreDataProperties.swift)。我还有一个 PersistenceController,它使用模型名称 JobLinkModel 初始化 NSPersistentContainer。
当我尝试使用以下方法保存新的 AppleUser 对象时:
让用户 = AppleUser(上下文:viewContext)
user.id = UUID()
user.name = “用户 1”
user.email = “...”
user.password = “密码 1”
user.createdAt = Date()【电子邮件格式正确,但已替换为“...”出于隐私原因】
尝试?viewContext.save()
我在控制台中收到以下错误:核心数据保存失败:Foundation._GenericObjCError.nilError, [:]
用户快照: [“id”: ..., “name”: “User1”, “email”: “...”, “password”: “...”, “createdAt”: ...]
所有字段都有有效值,核心数据模型似乎正确。我还尝试过:
• 检查 NSPersistentContainer(name:) 中的模型名称是否与 .xcdatamodeld 文件 (JobLinkModel) 匹配
• 确保正确设置 AppleUser 实体类、模块和 Codegen(类定义、当前产品模块)
• 删除重复或旧的 AppleUser 类文件
• 清理 Xcode 构建文件夹并从模拟器中删除应用程序
• 对上下文使用 @Environment(.managedObjectContext)
尽管如此,在保存新的 AppleUser 对象时,我仍然会收到 _GenericObjCError.nilError。
我想了解:
为什么即使所有字段都不是零且正确分配,核心数据也无法保存?
这可能是由于一些残留的旧类文件引起的,还是我缺少设置中的其他内容?
我应该采取哪些步骤来确保 Core Data 正确识别 AppleUser 实体并允许保存?
任何帮助或指导将不胜感激。
                    
                  
                
                    
                      I'm working on a new app with SwiftData and now adding CloudKit Sync.
Everything is working fine in the simulator against the development CloudKit Schema. I successfully deployed the schema to production.
However, the TestFlight builds fail against production. This is what I see in the logs, but I haven't been able to find info on how to fix it.
Help appreciated.
CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2205): <private> - Never successfully initialized and cannot execute request '<private>' due to error: Error Domain=CKErrorDomain Code=2 "CKInternalErrorDomain: 1011" UserInfo={ContainerID=<private>, NSDebugDescription=CKInternalErrorDomain: 1011, CKPartialErrors=<private>, RequestUUID=<private>, NSLocalizedDescription=<private>, CKErrorDescription=<private>, NSUnderlyingError=0x1078e9fe0 {Error Domain=CKInternalErrorDomain Code=1011 UserInfo={CKErrorDescription=<private>, NSLocalizedDescription=<private>, CKPartialErrors=<private>}}}
CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1153): <private>: Successfully set up CloudKit integration for store (<private>): <private>
CoreData+CloudKit: -[NSCloudKitMirroringDelegate _enqueueRequest:]_block_invoke(1035): Failed to enqueue request: <private>
Error Domain=NSCocoaErrorDomain Code=134417 UserInfo={NSLocalizedFailureReason=<private>}
                    
                  
                
                    
                      Hi everyone,
Complete newbie here. Building an app and trying to use Cloudkit. I've added the CloudKit capability, triple checked the entitlements file for appropriate keys, made sure the code signing entitlements are pointing to the correct entitlements file. I've removed and cleared all of those settings and even created a new container as well as refreshed the signing. I just can't seem to figure out why I keep getting this error:
Significant issue at CKContainer.m:747: In order to use CloudKit, your process must have a com.apple.developer.icloud-services entitlement. The value of this entitlement must be an array that includes the string "CloudKit" or "CloudKit-Anonymous".
Any guidance is greatly appreciated.
                    
                  
                
                    
                      Hi all,
In my SwiftUI / SwiftData / Cloudkit app which is a series of lists, I have a model object called Project which contains an array of model objects called subprojects:
final class Project1
{
    var name: String = ""
    
    @Relationship(deleteRule: .cascade, inverse: \Subproject.project) var subprojects : [Subproject]?
    
    init(name: String)
    {
        self.name = name
        self.subprojects = []
    }
}
The user will select a project from a list, which will generate a list of subprojects in another list, and if they select a subproject, it will generate a list categories and if the user selects a category it will generate another list of child objects owned by category and on and on.
This is the pattern in my app, I'm constantly passing arrays of model objects that are the children of other model objects throughout the program, and I need the user to be able to add and remove things from them.
My initial approach was to pass these arrays as bindings so that I'd be able to mutate them. This worked for the most part but there were two problems: it was a lot of custom binding code and when I had to unwrap these bindings using  init?(_ base: Binding<Value?>), my program would crash if one of these arrays became nil (it's some weird quirk of that init that I don't understand at al).
As I'm still learning the framework, I had not realized that the @model macro had automatically made my model objects observable, so I decided to remove the bindings and simply pass the arrays by reference, and while it seems these references will carry the most up to date version of the array, you cannot mutate them unless you have access to the parent and mutate it like such:
project.subcategories?.removeAll { $0 == subcategory }
project.subcategories?.append(subcategory)
This is weirding me out because you can't unwrap subcategories before you try to mutate the array, it has to be done like above. In my code, I like to unwrap all optionals at the moment that I need the values stored in them and if not, I like to post an error to the user. Isn't that the point of optionals? So I don't understand why it's like this and ultimately am wondering if I'm using the correct design pattern for what I'm trying to accomplish or if I'm missing something? Any input would be much appreciated!
Also, I do have a small MRE project if the explanation above wasn't clear enough, but I was unable to paste in here (too long), attach the zip or paste a link to Google Drive. Open to sharing it if anyone can tell me the best way to do so. Thanks!
                    
                  
                
                    
                      I'm implementing SwiftData with inheritance in an app.
I have an Entity class with a property name. This class is inherited by two other classes: Store and Person. The Entity model has a one-to-many relationship with a Transaction class.
I can list all my Entity models in a List with a @Query annotation without a problem.
However, then I try to access the name property of an Entity from a Transaction relationship, the app crashes with the following error:
Thread 1: Fatal error: Never access a full future backing data - PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(backing: SwiftData.PersistentIdentifier.PersistentIdentifierBacking.managedObjectID(0x96530ce28d41eb63 <x-coredata://DABFF7BB-C412-474E-AD50-A1F30AC6DBE9/Person/p4>))) with Optional(F07E7E23-F8F0-4CC0-B282-270B5EDDC7F3)
From my attempts to fix the issue, I noticed that:
The crash seems related to the relationships with classes that has inherit from another class, since it only happens there.
When I create new data, I can usually access it without any problem. The crash mostly happens after reloading the app.
This error has been mentioned on the forum (for example here), but in a context not related with inheritance.
You can find the full code here.
For reference, my models looks like this:
@Model
class Transaction {
	@Attribute(.unique)
	var id: String
	var name: String
	var date: Date
	var amount: Double
	var entity: Entity?
	var store: Store? { entity as? Store }
	var person: Person? { entity as? Person }
	
	init(
		id: String = UUID().uuidString,
		name: String,
		amount: Double,
		date: Date = .now,
		entity: Entity? = nil,
	) {
		self.id = id
		self.name = name
		self.amount = amount
		self.date = date
		self.entity = entity
	}
}
@Model
class Entity: Identifiable {
	@Attribute(.preserveValueOnDeletion)
	var name: String
	var lastUsedAt: Date
	@Relationship(deleteRule: .cascade, inverse: \Transaction.entity)
	var operations: [Transaction]
	
	init(
		name: String,
		lastUsedAt: Date = .now,
		operations: [Transaction] = [],
	) {
		self.name = name
		self.lastUsedAt = lastUsedAt
		self.operations = operations
	}
}
@available(iOS 26, *)
@Model
class Store: Entity {
	@Attribute(.unique) var id: String
	var locations: [Location]
	
	init(
		id: String = UUID().uuidString,
		name: String,
		lastUsedAt: Date = .now,
		locations: [Location] = [],
		operations: [Transaction] = []
	) {
		self.locations = locations
		self.id = id
		super.init(name: name, lastUsedAt: lastUsedAt, operations: operations)
	}
}
In order to reproduce the error:
Run the app in the simulator.
Click the + button to create a new transaction.
Relaunch the app, then click on any transaction.
The app crashes when it tries to read te name property while building the details view.
                    
                  
                
                    
                      Good morning everyone!
Today I have a question about using SwiftData with CloudKit and Widgets. I recently set up my project for SwiftData and CloudKit synchronization, but for some reason, I’m not able to give my Widget access to this data. CloudKit works perfectly fine for my main app, but the Widget only shows placeholder data(the placeholder data which were defined in the get functions as catch, this is sure).
I have set the CloudKit capability for my Widget extension and tried fetching data with the get-functions in the code below. I also ensured that the data model files are members of the Widget extension target and that the Widget extension uses the same CloudKit container as the main app.
I wondered if it is possible and reasonable to save a copy of my CloudKit data in an App Group container, but in that case, the information shown in the Widget are not always up-to-date, so a solution that fetches data directly from CloudKit would be better. Has anyone had experience with this case? I couldn’t find much information about this problem online.
In the code below, many parts have been deleted or altered because they are not relevant to the problem, as they don’t fetch data. The variables, functions, and data models in the code may sometimes have German names, but I hope you can still understand it.
Thanks for your help!
struct Provider: AppIntentTimelineProvider {
     
    //[Placeholder and snapshot]
     func timeline(for configuration: ConfigurationAppIntent, in context: Context) async -> Timeline<CleverEntry> {
         let entry = await loadAllVariables()
         return Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(60 * 5)))
     }
     
     @MainActor
     private func getExam() -> [PruefungM] {
        //Old, local version
         /*
         guard let modelContainer = try? ModelContainer(for: PruefungM.self) else {
             return []
         }
         let descriptor = FetchDescriptor<PruefungM>()
         let PRF = try? modelContainer.mainContext.fetch(descriptor)
         return PRF ?? []
         */
         do {
             let configuration = ModelConfiguration(cloudKitDatabase: .private("iCloud.my_bundle_id"))
             let container = try ModelContainer(
                 for: PruefungM.self,
                 configurations: configuration
             )
             let descriptor = FetchDescriptor<PruefungM>()
             return try container.mainContext.fetch(descriptor)
         } catch {
             print("❌ Error(CloudKit): \(error)")
             return []
         }
     }
@MainActor
     private func getHAF() -> [HausaufgabeM] {
         do {
             let configuration = ModelConfiguration(cloudKitDatabase: .private("iCloud.my_bundle_id"))
             let container = try ModelContainer(
                 for: HausaufgabeM.self,
                 configurations: configuration
             )
             let descriptor = FetchDescriptor<HausaufgabeM>()
             return try container.mainContext.fetch(descriptor)
         } catch {
             print("❌ Error (CloudKit): \(error)")
             return []
         }
     }
     @MainActor
     private func loadAllVariables() -> CleverEntry {
         print("Function started")
         let HAF = getHAF()
         let PRF = getExam()
         
         //handling and returning the data
     }
 }
                    
                  
                
                    
                      I'm trying to use the new (in tvOS 26) video streaming service automatic login API from the VideoSubscriberAccount framework:
https://developer.apple.com/documentation/videosubscriberaccount/vsuseraccountmanager/autosignintoken-swift.property
It seems that this API requires an entitlement. This document suggests that the com.apple.smoot.subscriptionservice entitlement is required.
https://developer.apple.com/documentation/videosubscriberaccount/signing-people-in-to-media-apps-automatically
However, it seems more likely that com.apple.developer.video-subscriber-single-sign-on is the correct entitlement.
https://developer.apple.com/documentation/bundleresources/entitlements/com.apple.developer.video-subscriber-single-sign-on
Which is the correct entitlement and how do I obtain it?
I don't want to fully comply with the video partner program.
https://developer.apple.com/programs/video-partner/
I just want to use this one new automatic login feature.