I built a SwiftData App that relies on CloudKit to synchronize data across devices.
That means all model relationships must be expressed as Optional.
That’s fine, but there is a limitation in using Optional’s in SwiftData SortDescriptors (Crashes App)
That means I can’t apply a SortDescriptor to ModelA using some property value in ModelB (even if ModelB must exist)
I tried using a computed property in ModelA that referred to the property in ModelB, BUT THIS DOESN”T WORK EITHER!
Am I stuck storing redundant data In ModelA just to sort ModelA as I would like???
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 getting a very odd error log in my SwiftData setup for an iOS app. It is implemented to support schema migration. When starting the app, it simply prints the following log twice (seems to be dependent on how many migration steps, I have two steps in my sample code):
CoreData: error: Attempting to retrieve an NSManagedObjectModel version checksum while the model is still editable. This may result in an unstable verison checksum. Add model to NSPersistentStoreCoordinator and try again.
(Yes there is a mistyped word "verison", this is exactly the log)
The code actually fully works. But I have neither CloudKit configured, nor is this app in Production yet. I'm still just developing.
Here is the setup and code to reproduce the issue.
Development mac version: macOS 15.5
XCode version: 16.4
iOS Simulator version: 18.5
Real iPhone version: 18.5
Project name: SwiftDataDebugApp
SwiftDataDebugApp.swift:
import SwiftUI
import SwiftData
@main
struct SwiftDataDebugApp: App {
var sharedModelContainer: ModelContainer = {
let schema = Schema([
Item.self,
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false, allowsSave: true)
do {
return try ModelContainer(for: schema, migrationPlan: ModelMigraitonPlan.self, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(sharedModelContainer)
}
}
Item.swift:
import Foundation
import SwiftData
typealias Item = ModelSchemaV2_0_0.Item
enum ModelSchemaV1_0_0: VersionedSchema {
static var versionIdentifier = Schema.Version(1, 0, 0)
static var models: [any PersistentModel.Type] {
[Item.self]
}
@Model
final class Item {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
}
enum ModelSchemaV2_0_0: VersionedSchema {
static var versionIdentifier = Schema.Version(2, 0, 0)
static var models: [any PersistentModel.Type] {
[Item.self]
}
@Model
final class Item {
var timestamp: Date
var tags: [Tag] = []
init(timestamp: Date, tags: [Tag]) {
self.timestamp = timestamp
self.tags = tags
}
}
}
enum ModelMigraitonPlan: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[ModelSchemaV1_0_0.self]
}
static var stages: [MigrationStage] {
[migrationV1_0_0toV2_0_0]
}
static let migrationV1_0_0toV2_0_0 = MigrationStage.custom(
fromVersion: ModelSchemaV1_0_0.self,
toVersion: ModelSchemaV2_0_0.self,
willMigrate: nil,
didMigrate: { context in
let items = try context.fetch(FetchDescriptor<ModelSchemaV2_0_0.Item>())
for item in items {
item.tags = Array(repeating: "abc", count: Int.random(in: 0...3)).map({ Tag(value: $0) })
}
try context.save()
}
)
}
Tag.swift:
import Foundation
struct Tag: Codable, Hashable, Comparable {
var value: String
init(value: String) {
self.value = value
}
static func < (lhs: Tag, rhs: Tag) -> Bool {
return lhs.value < rhs.value
}
static func == (lhs: Tag, rhs: Tag) -> Bool {
return lhs.value == rhs.value
}
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
ContentView.swift:
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var items: [Item]
var body: some View {
VStack {
List {
ForEach(items) { item in
VStack(alignment: .leading) {
Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
HStack {
ForEach(item.tags, id: \.hashValue) { tag in
Text("\(tag.value)")
}
}
}
}
.onDelete(perform: deleteItems)
}
Button("Add") {
addItem()
}
.padding(.top)
}
}
private func addItem() {
withAnimation {
let newItem = Item(timestamp: Date(), tags: [Tag(value: "Hi")])
modelContext.insert(newItem)
}
do {
try modelContext.save()
} catch {
print("Error saving add: \(error.localizedDescription)")
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(items[index])
}
}
do {
try modelContext.save()
} catch {
print("Error saving delete: \(error.localizedDescription)")
}
}
}
#Preview {
ContentView()
.modelContainer(for: Item.self, inMemory: true)
}
I hope someone can help, couldn't find anything related to this log at all.
I am using SwiftData to model my data. For that i created a model called OrganizationData that contains various relationships to other entities. My data set is quite large and i am having a big performance issue when fetching all OrganizationData entities. I started debugging and looking at the sql debug log i noticed that when fetching my entities i run into faults for all relationships even when not accessing them.
Fetching my entities:
let fetchDescriptor = FetchDescriptor<OrganizationData>()
let context = MapperContext(dataManager: self)
let organizations = (try modelContainer.mainContext.fetch(fetchDescriptor))
Doing this fetch, also fetches all relationships. Each in a single query, for every OrganizationData entity.
CoreData: annotation: to-many relationship fault "relationship1" for objectID 0x8aa5249772916e00 <x-coredata://B891FCEB-DF16-4E11-98E6-0AFB5D171A81/OrganizationData/p3869> fulfilled from database. Got 9 rows
CoreData: annotation: to-many relationship fault "relationship2" for objectID 0x8aa5249772916e00 <x-coredata://B891FCEB-DF16-4E11-98E6-0AFB5D171A81/OrganizationData/p3869> fulfilled from database. Got 0 rows
CoreData: annotation: to-many relationship fault "relationship3" for objectID 0x8aa5249772916e00 <x-coredata://B891FCEB-DF16-4E11-98E6-0AFB5D171A81/OrganizationData/p3869> fulfilled from database. Got 0 rows
CoreData: annotation: to-many relationship fault "relationship4" for objectID 0x8aa5249772916e00 <x-coredata://B891FCEB-DF16-4E11-98E6-0AFB5D171A81/OrganizationData/p3869> fulfilled from database. Got 0 rows
CoreData: annotation: to-many relationship fault "relationship5" for objectID 0x8aa5249772916e00 <x-coredata://B891FCEB-DF16-4E11-98E6-0AFB5D171A81/OrganizationData/p3869> fulfilled from database. Got 0 rows
CoreData: annotation: to-many relationship fault "relationship6" for objectID 0x8aa5249772916e00 <x-coredata://B891FCEB-DF16-4E11-98E6-0AFB5D171A81/OrganizationData/p3869> fulfilled from database. Got 0 rows
CoreData: annotation: to-many relationship fault "relationship7" for objectID 0x8aa5249772916e00 <x-coredata://B891FCEB-DF16-4E11-98E6-0AFB5D171A81/OrganizationData/p3869> fulfilled from database. Got 1 rows
CoreData: annotation: to-many relationship fault "relationship8" for objectID 0x8aa5249772916e00 <x-coredata://B891FCEB-DF16-4E11-98E6-0AFB5D171A81/OrganizationData/p3869> fulfilled from database. Got 0 rows
CoreData: annotation: to-many relationship fault "relationship9" for objectID 0x8aa5249772916e00 <x-coredata://B891FCEB-DF16-4E11-98E6-0AFB5D171A81/OrganizationData/p3869> fulfilled from database. Got 0 rows
The relationships are all defined the same
@Relationship(deleteRule: .cascade, inverse: \EntityData1.organization)
var relationship1: [EntityData1] = []
Am i missing something? As far as i understood relationships are lazy and should only be faulted when accessing the property. But doing the fetch as described above already causes a query to happen, making the fetch take very long when using a large data set.
Hey all,
This is my first app with Swift, and first app using CloudKit / iCloud - although I have launched other iOS app successfully.
When I created the app, I selected "none" for storage
my bundle identifier looks like this: io.mysite.appname
I have the iCloud capability added, with CloudKit checked, and the container also checked that looks like this: iCloud.io.mysite.appname
Push Notificaitons capability is also added, but there is no configuration.
I have tried automatically managed signing, as well as a manually created provisioning profile..
Every time I build the app onto my device - when I check it out in settings, icloud is not listed. When I go through iCloud into icloud drive, the app is also not listed.
I have cleaned the build many times, deleted and reinstalled the app on my phone many times. I am definitely logged into iCloud etc.
Obviously I have spent plenty of times trying to debug with various LLMs, but we all seem to be at a loss for what I'm missing or doing wrong.
Would love any tips or pointers I may be missing, thank you!
Topic:
App & System Services
SubTopic:
iCloud & Data
I am trying to extend my PersistedModels like so:
@Versioned(3)
@Model
class MyType {
var name: String
init() { name = "hello" }
}
but it seems that SwiftData's@Model macro is unable to read the properties added by my @Versioned macro. I have tried changing the order and it ignores them regardless. version is not added to schemaMetadata and version needs to be persisted. I was planning on using this approach to add multiple capabilities to my model types. Is this possible to do with macros?
VersionedMacro
/// A macro that automatically implements VersionedModel protocol
public struct VersionedMacro: MemberMacro, ExtensionMacro {
// Member macro to add the stored property directly to the type
public static func expansion(
of node: AttributeSyntax,
providingMembersOf declaration: some DeclGroupSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
guard let argumentList = node.arguments?.as(LabeledExprListSyntax.self),
let firstArgument = argumentList.first?.expression else {
throw MacroExpansionErrorMessage("@Versioned requires a version number, e.g. @Versioned(3)")
}
let versionValue = firstArgument.description.trimmingCharacters(in: .whitespaces)
// Add the stored property with the version value
return [
"public private(set) var version: Int = \(raw: versionValue)"
]
}
// Extension macro to add static property
public static func expansion(
of node: SwiftSyntax.AttributeSyntax,
attachedTo declaration: some SwiftSyntax.DeclGroupSyntax,
providingExtensionsOf type: some SwiftSyntax.TypeSyntaxProtocol,
conformingTo protocols: [SwiftSyntax.TypeSyntax],
in context: some SwiftSyntaxMacros.MacroExpansionContext
) throws -> [SwiftSyntax.ExtensionDeclSyntax] {
guard let argumentList = node.arguments?.as(LabeledExprListSyntax.self),
let firstArgument = argumentList.first?.expression else {
throw MacroExpansionErrorMessage("@Versioned requires a version number, e.g. @Versioned(3)")
}
let versionValue = firstArgument.description.trimmingCharacters(in: .whitespaces)
// We need to explicitly add the conformance in the extension
let ext = try ExtensionDeclSyntax("extension \(type): VersionedModel {}")
.with(\.memberBlock.members, MemberBlockItemListSyntax {
MemberBlockItemSyntax(decl: DeclSyntax(
"public static var version: Int { \(raw: versionValue) }"
))
})
return [ext]
}
}
VersionedModel
public protocol VersionedModel: PersistentModel {
/// The version of this particular instance
var version: Int { get }
/// The type's current version
static var version: Int { get }
}
Macro Expansion:
Hi,
I am testing a situation with shared CKRecords where the data in the CKRecord syncs fine, but the creatorUserRecordID.recordName and lastModifiedUserRecordID.recordName shows "defaultOwner" (which maps to the CKCurrentUserDefaultName constant) even though I made sure I edit the CKRecord value from a different iCloud account. In fact, on the CloudKit dashboard, it shows the correct user recordIDs in the metadata for the 'Created' and 'Modified' fields, but not in the CKRecord.
I am mostly testing this on the iPhone simulator with the debugger attached. Is that a possible reason for this, or is there some other reason the lastModifiedUserRecordID is showing the value for 'CKCurrentUserDefaultName'? It would be pretty difficult to build in functionality to look up changes by a different userID if this is the case.
Hi, I work on a financial app in Brazil and since Beta 1 we're getting several crashes. We already opened a code level support and a few feedback issues, but haven't got any updates on that yet.
We were able to resolve some crashes changing some of our implementation but we aren't able to understand what might be happening with this last one.
This is the log we got on console:
erro 11:55:41.805875-0300 MyApp CoreData: error: Failed to load NSManagedObjectModel with URL 'file:///private/var/containers/Bundle/Application/0B9F47D9-9B83-4CFF-8202-3718097C92AE/MyApp.app/ServerDrivenModel.momd/'
We double checked and the momd is inside the bundle. The same app works on any other iOS version and if we build using Xcode directly (without archiving and installing on an iOS26 device) it works as expected.
Have anyone else faced a similar error? Any tips or advice on how we can try to solve that?
I have an app that uses CKShare to allow users to share CloudKit data with other users.
With the first build of the iOS 26, I'm seeing a few issues:
I'm not able to add myself as a participant anymore when I have the link to a document.
Some participants names no longer show up in the app.
Looking at the release notes for iOS & iPadOS 26 Beta, there is a CloudKit section with two bullets:
CloudKit sharing URLs do not launch third-party apps. (151778655)
The request access APIs, such as CKShareRequestAccessOperation, are available in the SDK but are currently nonfunctional. (151878020)
It sounds like the first issue is addressed by the first bullet, although the error message makes me wonder if I need to make changes to my iCloud account permissions or something in order to open it. It works fine in iOS 18.5. This is the error I get when I try to open a link to a shared document (I blocked out my email address, which is what was in quotes):
As far as the second issue, I am really confused about what is going on. Some names still show up, while others do not. I can't find a pattern, and the missing users are not on the iOS 26 beta. The release notes mention CKShareRequestAccessOperation being nonfunctional, which is new in the beta and has some minor documentation, but I can't find information about how it's supposed to be used yet.
In previous years there have been WWDC sessions about what's new in CloudKit, but I haven't found anything that talks about these changes to document sharing.
Is there a guide or session somewhere that I'm missing?
Does anyone know what's going on with these changes to CloudKit?
Hi,
I am experiencing main thread freezes from fetching on Main Actor. Attempting to move the function to a background thread, but whenever I reference the TestModel in a nonisolated context or in another model actor, I get this warning:
Main actor-isolated conformance of 'TestModel' to 'PersistentModel' cannot be used in actor-isolated context; this is an error in the Swift 6 language mode
Is there a way to do this correctly?
Recreation, warning on line 13:
class TestModel {
var property: Bool = true
init() {}
}
struct SendableTestModel: Sendable {
let property: Bool
}
@ModelActor
actor BackgroundActor {
func fetch() throws -> [SendableTestModel] {
try modelContext.fetch(FetchDescriptor<TestModel>()).map { SendableTestModel(property: $0.property) }
}
}
Hi,
I'm considering using the new SwiftData class inheritance for a new app I'm building. I have a few questions:
Is it working well enough for production?
I have a number of different object types in my app. Some of them are very similar, and there's always a balance to be struck when it comes to splitting them into different types using class inheritance. Are there some good advice on when to use multiple classes instead of squeezing my object types into a single class?
Is there advice against using class inheritance in multiple levels (3-4)?
Claes
About 4 months ago, I shipped the first version of my app with 4 versioned schemas that, unintentionally, had the same versionIdentifier of 1.2.0 in 2 of them:
V1: 1.0.0
V2: 1.1.0
V3: 1.2.0
V4: 1.2.0
They are ordered correctly in the MigrationPlan, and they are all lightweight.
Migration works, SwiftData doesn't crash on init and I haven't encountered any issues related to this. The app syncs with iCloud.
Questions, preferable for anybody with knowledge of SwiftData internals:
What will break in SwiftData when there are 2 duplicate numbers?
Not that I would expect it to be safe, but does it happen to be safe to ship an update that changes V4's version to 1.3.0, what was originally intended?
Topic:
App & System Services
SubTopic:
iCloud & Data
Hi, I keep trying to use transformable to store an array of strings with SwiftData, and I can see that it is activating the transformer, but it keeps saying that I am still using NSArray instead of NSData.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "category"; desired type = NSData; given type = Swift.__SwiftDeferredNSArray; value = (
yo,
gurt
).'
terminating due to uncaught exception of type NSException
CoreSimulator 1010.10 - Device: iPhone 16 18.0 (6879535B-3174-4025-AD37-ED06E60291AD) - Runtime: iOS 18.0 (22A3351) - DeviceType: iPhone 16
Message from debugger: killed
@Model
class MyModel: Identifiable, Equatable {
@Attribute(.transformable(by: StringArrayTransformer.self)) var category: [String]?
@Attribute(.transformable(by: StringArrayTransformer.self)) var amenities: [String]?
var image: String?
var parentChunck: HenricoPostDataChunk_V1?
init(category: [String]?, amenities: [String]?) {
self.category = category
self.amenities = amenities
}
}
class StringArrayTransformer: ValueTransformer {
override func transformedValue(_ value: Any?) -> Any? {
print(value)
guard let array = value as? [String] else { return nil }
let data = try? JSONSerialization.data(withJSONObject: array, options: [])
print(data)
return data
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
guard let data = value as? Data else { return nil }
let string = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String]
print(string)
return string
}
override class func transformedValueClass() -> AnyClass {
return NSData.self
}
override class func allowsReverseTransformation() -> Bool {
return true
}
static func register() {
print("regitsering")
ValueTransformer.setValueTransformer(StringArrayTransformer(), forName: .stringArrayTransformerName)
}
}
extension NSValueTransformerName {
static let stringArrayTransformerName = NSValueTransformerName("StringArrayTransformer")
}
I have an app that uses NSPersistentCloudKitContainer stored in a shared location via App Groups so my widget can fetch data to display. It works. But if you reset your iPhone and restore it from a backup, an error occurs:
The file "Name.sqlite" couldn't be opened. I suspect this happens because the widget is created before the app's data is restored. Restarting the iPhone is the only way to fix it though, opening the app and reloading timelines does not. Anything I can do to fix that to not require turning it off and on again?
Hi, I keep trying to use transformable to store an array of strings with SwiftData, and I can see that it is activating the transformer, but it keeps saying that I am still using NSArray instead of NSData.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "category"; desired type = NSData; given type = Swift.__SwiftDeferredNSArray; value = ( yo, gurt ).' terminating due to uncaught exception of type NSException CoreSimulator 1010.10 - Device: iPhone 16 18.0 (6879535B-3174-4025-AD37-ED06E60291AD) - Runtime: iOS 18.0 (22A3351) - DeviceType: iPhone 16 Message from debugger: killed
@Model
class MyModel: Identifiable, Equatable {
@Attribute(.transformable(by: StringArrayTransformer.self)) var category: [String]?
@Attribute(.transformable(by: StringArrayTransformer.self)) var amenities: [String]?
var image: String?
var parentChunck: MyModelDataChunk_V1?
init(category: [String]?, amenities: [String]?) {
self.category = category
self.amenities = amenities
}
}
class StringArrayTransformer: ValueTransformer {
override func transformedValue(_ value: Any?) -> Any? {
print(value)
guard let array = value as? [String] else { return nil }
let data = try? JSONSerialization.data(withJSONObject: array, options: [])
print(data)
return data
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
guard let data = value as? Data else { return nil }
let string = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String]
print(string)
return string
}
override class func transformedValueClass() -> AnyClass {
return NSData.self
}
override class func allowsReverseTransformation() -> Bool {
return true
}
static func register() {
print("regitsering")
ValueTransformer.setValueTransformer(StringArrayTransformer(), forName: .stringArrayTransformerName)
}
}
extension NSValueTransformerName {
static let stringArrayTransformerName = NSValueTransformerName("StringArrayTransformer")
}
I'm trying to convert some data, then save it back to Core Data. Sometimes this works fine without an issue, but occasionally I'll get an error
Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
It seems to occur when saving the core data context. I'm having trouble trying to debug it as it doesn't happen on the same object each time and can't reliably recreate the error
Full view code can be found https://pastebin.com/d974V5Si but main functions below
var body: some View {
VStack {
// Visual code here
}
.onAppear() {
DispatchQueue.global(qos: .background).async {
while (getHowManyProjectsToUpdate() > 0) {
leftToUpdate = getHowManyProjectsToUpdate()
updateLocal()
}
if getHowManyProjectsToUpdate() == 0 {
while (getNumberOfFilesInDocumentsDirectory() > 0) {
deleteImagesFromDocumentsDirectory()
}
if getNumberOfFilesInDocumentsDirectory() == 0 {
DispatchQueue.main.asyncAfter(deadline: .now()) {
withAnimation {
self.isActive = true
}
}
}
}
}
}
}
update local function
func updateLocal() {
autoreleasepool {
let fetchRequest: NSFetchRequest<Project> = Project.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "converted = %d", false)
fetchRequest.fetchLimit = 1
fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Project.name, ascending: true), NSSortDescriptor(keyPath: \Project.name, ascending: true)]
do {
let projects = try viewContext.fetch(fetchRequest)
for project in projects {
currentPicNumber = 0
currentProjectName = project.name ?? "Error loading project"
if let projectMain = project.mainPicture {
currentProjectImage = getUIImage(picture: projectMain)
}
if let pictures = project.pictures {
projectPicNumber = pictures.count
// Get main image
if let projectMain = project.mainPicture {
if let imgThumbData = convertImageThumb(picture: projectMain) {
project.mainPictureData = imgThumbData
}
}
while (getTotalImagesToConvertForProject(project: project ) > 0) {
convertImageBatch(project: project)
}
project.converted = true
saveContext()
viewContext.refreshAllObjects()
}
}
} catch {
print("Fetch Failed")
}
}
}
convertImageBatch function
func convertImageBatch(project: Project) {
autoreleasepool {
let fetchRequestPic: NSFetchRequest<Picture> = Picture.fetchRequest()
let projectPredicate = NSPredicate(format: "project = %@", project)
let dataPredicate = NSPredicate(format: "pictureData == NULL")
fetchRequestPic.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [projectPredicate, dataPredicate])
fetchRequestPic.fetchLimit = 5
fetchRequestPic.sortDescriptors = [NSSortDescriptor(keyPath: \Picture.dateTaken, ascending: true)]
do {
let pictures = try viewContext.fetch(fetchRequestPic)
for picture in pictures {
currentPicNumber = currentPicNumber + 1
if let imgData = convertImage(picture: picture), let imgThumbData = convertImageThumb(picture: picture) {
// Save Converted
picture.pictureData = imgData
picture.pictureThumbnailData = imgThumbData
// Save Image
saveContext()
viewContext.refreshAllObjects()
} else {
viewContext.delete(picture)
saveContext()
viewContext.refreshAllObjects()
}
}
} catch {
print("Fetch Failed")
}
}
}
And finally saving
func saveContext() {
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
Good Morning I am building a app that uses cloudkit and am trying to find our the app limits allowed
I have been trying to find out the app limits to my app when released into the app store, I understand that in the public database the app worldwide can use 200g of bandwidth free per month. What happens after that? is it throttled? is there a pricing structure for overages? thanks
I have an app with fairly typical requirements - I need to insert some data (in my case from the network but could be anything) and I want to do it in the background to keep the UI responsive.
I'm using SwiftData.
I've created a ModelActor that does the importing and using the debugger I can confirm that the data is indeed being inserted.
On the UI side, I'm using @Query and a SwiftUI List to display the data but what I am seeing is that @Query is not updating as the data is being inserted. I have to quit and re-launch the app in order for the data to appear, almost like the context running the UI isn't communicating with the context in the ModelActor.
I've included a barebones sample project. To reproduce the issue, tap the 'Background Insert' button. You'll see logs that show items being inserted but the UI is not showing any data.
I've tested on the just released iOS 18b3 seed (22A5307f).
The sample project is here:
https://hanchor.s3.amazonaws.com/misc/SwiftDataBackgroundV2.zip
I have tried to set up iCloud sync. Despite fully isolating and resetting my development environment, the app fails with:
NSCocoaErrorDomain Code=134060 (PersistentStoreIncompatibleVersionHashError)
What I’ve done:
Created a brand new CloudKit container
Created a new bundle ID and app target
Renamed the Core Data model file itself
Set a new model version
Used a new .sqlite store path
Created a new .entitlements file with the correct container ID
Verified that the CloudKit dashboard shows no records
Deleted and reinstalled the app on a real device
Also tested with “Automatically manage signing” and without
Despite this, the error persists. I am very inexperienced and am not sure what my next step is to even attempt to fix this. Any guidance is apprecitated.
Hi all,
I recently discovered that I forgot to deploy my CloudKit schema changes from development to production - an oversight that unfortunately went unnoticed for 2.5 months.
As a result, any data created during that time was never synced to iCloud and remains only in the local CoreData store. Once I pushed the schema to production, CloudKit resumed syncing new changes as expected.
However, this leaves me with a gap: there's now a significant amount of data that would be lost if users delete or reinstall the app.
Before I attempt to implement a manual backup or migration strategy, I was wondering:
Does NSPersistentCloudKitContainer keep track of local changes that couldn't be synced doe to the missing schema and automatically reattempt syncing them now that the schema is live?
If not, what would be the best approach to ensure this "orphaned" data gets saved to CloudKit retroactively.
Thanks in advance for any guidance or suggestions.
anyone getting the following error with CloudKit+CoreData on iOS16 RC?
delete/resintall app, delete user CloudKit data and reset of environment don't fix.
[error] error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2044): <NSCloudKitMirroringDelegate: 0x2816f89a0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringImportRequest: 0x283abfa00> 41E6B8D6-08C7-4C73-A718-71291DFA67E4' due to error: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)}