I'm trying to look at what the best way to do thumbnails for images that are saved in core data, which are being synced across multiple devices.
I know I can save a lower quality version into core data, but I'm wondering if there's a better way of doing it.
I've come across quick look thumbnailing which looks like what I want, but I'm not sure if it can be adapted for core data as its using file paths, whereas the images are stored in a data type property in core data.
From what I can tell, I'd have to save the image locally, produce the thumbnail, then delete the local image
iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
Post
Replies
Boosts
Views
Activity
Hello,
SwiftData is not working correctly with Swift Concurrency. And it’s sad after all this time.
I personally found a regression. The attached code works perfectly fine on iOS 17.5 but doesn’t work correctly on iOS 18 or iOS 18.1.
A model can be updated from the background (Task, Task.detached or ModelActor) and refreshes the UI, but as soon as the same item is updated from the View (fetched via a Query), the next background updates are not reflected anymore in the UI, the UI is not refreshed, the updates are not merged into the main.
How to reproduce:
Launch the app
Tap the plus button in the navigation bar to create a new item
Tap on the “Update from Task”, “Update from Detached Task”, “Update from ModelActor” many times
Notice the time is updated
Tap on the “Update from View” (once or many times)
Notice the time is updated
Tap again on “Update from Task”, “Update from Detached Task”, “Update from ModelActor” many times
Notice that the time is not update anymore
Am I doing something wrong? Or is this a bug in iOS 18/18.1?
Many other posts talk about issues where updates from background thread are not merged into the main thread. I don’t know if they all are related but it would be nice to have
1/ bug fixed, meaning that if I update an item from a background, it’s reflected in the UI, and
2/ proper documentation on how to use SwiftData with Swift Concurrency (ModelActor). I don’t know if what I’m doing in my buttons is correct or not.
Thanks,
Axel
import SwiftData
import SwiftUI
@main
struct FB_SwiftData_BackgroundApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.modelContainer(for: Item.self)
}
}
}
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@State private var simpleModelActor: SimpleModelActor!
@Query private var items: [Item]
var body: some View {
NavigationView {
VStack {
if let firstItem: Item = items.first {
Text(firstItem.timestamp, format: Date.FormatStyle(date: .omitted, time: .standard))
.font(.largeTitle)
.fontWeight(.heavy)
Button("Update from Task") {
let modelContainer: ModelContainer = modelContext.container
let itemID: Item.ID = firstItem.persistentModelID
Task {
let context: ModelContext = ModelContext(modelContainer)
guard let itemInContext: Item = context.model(for: itemID) as? Item else { return }
itemInContext.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000))
try context.save()
}
}
.buttonStyle(.bordered)
Button("Update from Detached Task") {
let container: ModelContainer = modelContext.container
let itemID: Item.ID = firstItem.persistentModelID
Task.detached {
let context: ModelContext = ModelContext(container)
guard let itemInContext: Item = context.model(for: itemID) as? Item else { return }
itemInContext.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000))
try context.save()
}
}
.buttonStyle(.bordered)
Button("Update from ModelActor") {
let container: ModelContainer = modelContext.container
let persistentModelID: Item.ID = firstItem.persistentModelID
Task.detached {
let actor: SimpleModelActor = SimpleModelActor(modelContainer: container)
await actor.updateItem(identifier: persistentModelID)
}
}
.buttonStyle(.bordered)
Button("Update from ModelActor in State") {
let container: ModelContainer = modelContext.container
let persistentModelID: Item.ID = firstItem.persistentModelID
Task.detached {
let actor: SimpleModelActor = SimpleModelActor(modelContainer: container)
await MainActor.run {
simpleModelActor = actor
}
await actor.updateItem(identifier: persistentModelID)
}
}
.buttonStyle(.bordered)
Divider()
.padding(.vertical)
Button("Update from View") {
firstItem.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000))
}
.buttonStyle(.bordered)
} else {
ContentUnavailableView(
"No Data",
systemImage: "slash.circle", //
description: Text("Tap the plus button in the toolbar")
)
}
}
.toolbar {
ToolbarItem(placement: .primaryAction) {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
}
}
private func addItem() {
modelContext.insert(Item(timestamp: Date.now))
try? modelContext.save()
}
}
@ModelActor
final actor SimpleModelActor {
var context: String = ""
func updateItem(identifier: Item.ID) {
guard let item = self[identifier, as: Item.self] else {
return
}
item.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000))
try! modelContext.save()
}
}
@Model
final class Item: Identifiable {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
The WWDC2024 custom data store example doesn't provide any details on how one would go about creating a DataStoreSnapshot. The example uses a DefaultSnapshot for persisting the data in the DefaultSnapshot format directly in the JSON file.
There appears to be no documentation or examples of how one might create a DataStoreSnapshot from data from another database.
The Apple documentation for DefaultSnapshot provides no examples of how one might create such a snapshot from data retrieved elsewhere.
Can anyone provide a simple example of how one might create such a snapshot from a remote database such that it can be returned as part of the response to a fetch request.
For the purpose of this example let's assume I have a CSV file with rows of data and code to read the data from this file. How would I create a snapshot or snapshots for each of the rows of data.
My app is able to receive data updates when it is in foreground.
however, when i move it in background then sync engine stops syncing until I again move app to foreground.
I'm trying to get the CoreDataCloudKitShare example to work, but having trouble. The first error I see when running the InitializeCloudKitSchema target (on macOS) is the following:
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1242): <NSCloudKitMirroringDelegate: 0x60000229c0f0>: Failed to set up CloudKit integration for store: <NSSQLCore: 0x15b807830> (URL: file:///Users/rmann/Library/Application%20Support/InitializeCloudKitSchema/CoreDataStores/Private/private.sqlite)
<CKError 0x600001311290: "Partial Failure" (2/1011); "Failed to modify some record zones"; uuid = 3E1B1380-AE1C-4B14-97A8-7F60B4A8F3EF; container ID = "iCloud.com.example.CoreDataCloudKitShareH6F2W964VK"; partial errors: {
com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x60000132f810: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = F3987848B25CEED7; uuid = 3E1B1380-AE1C-4B14-97A8-7F60B4A8F3EF>
}>
I see a database in the Dashboard with that container ID, but don't know what it means by "Invalid bundle ID for container". I've seen several other posts about this across the web, and the only answer is ever "seems to be an Apple issue, wait a bit."
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
}
}
My App requires access to iCloud. I used to be able to get the User's name components (family+given name) using:
let dummyZone = CKRecordZone (zoneName: UUID().uuidString)
let dummyShare = CKShare (recordZoneID: dummyZone.zoneID)
Persistence.logger.notice ("\(#function): Dummy Zone: \(dummyZone.zoneID.zoneName)")
// Save the dummyZone and then the dummyShare (for/in the dummyZone)
let _ = try await container.privateCloudDatabase.save (dummyZone)
let _ = try await container.privateCloudDatabase.save (dummyShare)
// Extract the dummyShare's owner's identity - which is 'us/me'
let userIdentity = dummyShare.owner.userIdentity
where the resulting userIdentity had a filled out nameComponents. Now, recently, it seems to be empty.
Did something change in the interfaces?
I've also tried, more directly:
let userRecordID = try await container.userRecordID()
let userParticipant = try await container.shareParticipant(forUserRecordID: userRecordID)
let userIdentity = userParticipant.userIdentity
and still nameComponents is empty.
Given that my App requires iCloud, is there a way to get (familyName,givenName)?
Use CloudKit's ckqueryoperation's recordmatchedblock in Swift 6.0, which always crashes, but works fine in Swift 5:
func fetchAllRecords() async throws {
let predicate = NSPredicate(format: "Topics = %@", "Integrations")
let query = CKQuery(recordType: "PureMList", predicate: predicate)
let operation = CKQueryOperation(query: query)
operation.recordMatchedBlock = { recordID, result in
switch result {
case .success(let record):
DispatchQueue.main.async {
// Ensure UI updates happen here
print("Fetched record: \(record)")
// Update your UI elements here
}
case .failure(let error):
// Handle the error
print("Error fetching record with ID \(recordID): \(error)")
}
}
// Ensure you're using the correct database
publicDatabase.add(operation)
}
I'm trying to write a SwiftUI iOS/macOS app that allows users to collaborate, but I keep running into limitations. The latest is that I can't figure out what the UICloudSharingContainer equivalent is on macOS. It doesn't seem like there’s a SwiftUI version of this, so I have to write a lot of platform-specific code to handle it, but it's not clear what the AppKit equivalent is.
Hello,
I have a problem with SwiftData and Predicates that check for the persistentModelID of the relations.
My data model looks simplified like this:
Day -> TimeEntry[] -> Hashtag[]
What I want to achieve is to query the days and associated time entries via assigned tags.
This is my predicate:
let identifier = filterHashtags.map(\.persistentModelID)
...
#Predicate<TimeEntry> { timeEntry in
identifiers.count == timeEntry.tags.filter { tag in
identifiers.contains(tag.persistentModelID)
}.count
}
It does not return any data when I check for the persistentModelID. However, if I use another property of the tags, e.g. the name or a generated UUID for the check, the predicate works. Is this a general problem with PersistentIdentifier in Predicates or am I missing something?
Thanks in advance
First off, given that I didn't find a tag for Code Review, I hope I am not out of scope for the forums here.
Second, some background. I am a long time Windows Power Shell developer, moving to Swift because I don't like self loathing. :)
Currently I am trying to get my head around SwiftData, and experimenting with creating a Service to handle the actual SwiftData functionality, and a Manager to handle various tasks that relate to instances of the Model. I am doing this realizing that it MAY NOT be the best approach, but it gives me reps both producing code and thinking about how to solve a problem, which I think is useful even if the actual product in throw away. That said, I am hoping someone with more experience than I can comment on this approach, especially with respect to expanding to more models, more complex models, lots of data and a desire to use ModelActor eventually.
DataManagerApp.swift
import SwiftData
import SwiftUI
@main
struct DataManagerApp: App {
let container: ModelContainer
init() {
let schema = Schema([DataModel.self])
let config = ModelConfiguration("SwiftDataStore", schema: schema)
do {
let modelContainer = try ModelContainer(for: schema, configurations: config)
DataService.instance.assignContainer(modelContainer)
container = modelContainer
} catch {
fatalError("Could not configure SwiftData ModelContainer.")
}
}
var body: some Scene {
WindowGroup {
ContentView()
.modelContainer(container)
}
}
}
DataModel.swift
import Foundation
import SwiftData
@Model
final class DataModel {
var date: Date
init(date: Date) {
self.date = date
}
}
final class DataService {
static let instance = DataService()
private var modelContainer: ModelContainer?
private var modelContext: ModelContext?
private init() {}
func assignContainer(_ container: ModelContainer) {
if modelContainer == nil {
modelContainer = container
modelContext = ModelContext(modelContainer!)
} else {
print("Attempted to assign ModelContainer more than once.")
}
}
func addModel(_ dataModel: DataModel) {
modelContext?.insert(dataModel)
}
func removeModel(_ dataModel: DataModel) {
modelContext?.delete(dataModel)
}
}
final class ModelManager {
static let instance = ModelManager()
let dataService: DataService = DataService.instance
private init() {}
func newModel() {
let newModel = DataModel(date: Date.now)
DataService.instance.addModel(newModel)
}
}
ContentView.swift
import SwiftData
import SwiftUI
struct ContentView: View {
@Environment(\.modelContext) var modelContext
@State private var sortOrder = SortDescriptor(\DataModel.date)
@Query(sort: [SortDescriptor(\DataModel.date)]) var models: [DataModel]
var body: some View {
VStack {
addButton
List {
ForEach(models) { model in
modelRow(model)
}
}
.listStyle(.plain)
}
.padding()
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
addButton
}
}
}
}
private extension ContentView {
var addButton: some View {
Button("+ Add") {
ModelManager.instance.newModel()
}
}
func modelRow(_ model: DataModel) -> some View {
HStack {
Text(model.date.formatted(date: .numeric, time: .shortened))
Spacer()
}
}
}
Hi,
I did cloudkit synchronization using swiftdata.
However, synchronization does not occur automatically, and synchronization occurs intermittently only when the device is closed and opened.
For confirmation, after changing the data in Device 1 (saving), when the data is fetched from Device 2, there is no change.
I've heard that there's still an issue with swiftdata sync and Apple is currently troubleshooting it, is the phenomenon I'm experiencing in the current version normal?
I've been struggling to get a ValueTransformer to work while developing in Xcode 16 for iOS 18. Despite thinking I had everything set up correctly, I keep encountering the following error whenever I create a tag:
let tag = Tag(name: name, color: color.toPlatformColor()) // Converts it to NSColor or UIColor
modelContext.insert(tag)
SwiftData/DataUtilities.swift:184: Fatal error: Unable to determine the primitive for Attribute - name: color, options: [transformable with Optional("ColorTransformer")], valueType: UIColor, defaultValue: UIExtendedSRGBColorSpace 0 0 1 1, hashModifier: nil
Here’s what I’m dealing with:
Tag Model:
@Model
public final class Tag: Identifiable {
var name: String = ""
@Attribute(.transformable(by: ColorTransformer.self))
var color: PlatformColor = PlatformColor.blue
init(name: String, color: PlatformColor) {
self.name = name
self.color = color
}
}
ColorTransformer:
final class ColorTransformer: ValueTransformer {
override func transformedValue(_ value: Any?) -> Any? {
guard let color = value as? PlatformColor else { return nil }
do {
let data = try NSKeyedArchiver.archivedData(
withRootObject: color, requiringSecureCoding: true)
return data
} catch {
assertionFailure("Failed to transform `PlatformColor` to `Data`")
return nil
}
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
guard let data = value as? NSData else { return PlatformColor.black }
do {
let color = try NSKeyedUnarchiver.unarchivedObject(
ofClass: PlatformColor.self, from: data as Data)
return color
} catch {
assertionFailure("Failed to transform `Data` to `PlatformColor`")
return nil
}
}
override class func transformedValueClass() -> AnyClass {
return PlatformColor.self
}
override class func allowsReverseTransformation() -> Bool {
return true
}
public static func register() {
ValueTransformer.setValueTransformer(ColorTransformer(), forName: .colorTransformer)
}
}
extension NSValueTransformerName {
static let colorTransformer = NSValueTransformerName(rawValue: "ColorTransformer")
}
Platform Alias:
#if os(macOS)
typealias PlatformColor = NSColor
#else
typealias PlatformColor = UIColor
#endif
The ValueTransformer is registered when the ModelContainer is created at app startup:
var sharedModelContainer: ModelContainer = {
ColorTransformer.register()
// Other configurations...
}()
I've also tried not aliasing the colors to see if that changes anything, but I still encounter the same issue. Any guidance or suggestions would be greatly appreciated!
I created a new index on two record types on Oct 12th. I still cannot query the records using the new queryable index on records that were created before that date. There is no indication in the schema history that the reindexing has started, completed, failed, or still in progress.
What is the expectation for new indices being applied to existing records? Well over a week seems unacceptable for a database that has maybe 5000 records across a few record types.
When I query my data using an old index and an old record field, I get hundreds of matching results so I know the data is there.
FB15554144 - CloudKit / CloudKit Console: PRODUCTION ISSUE - Query against index created two weeks ago not returning all data as expected
I'm considering using CloudKit in my app (it doesn't use Core Data) and have read as many materials as I can find. I haven't fully grasped it yet and have a basic question on CKRecord.Reference. Does CloudKit guarantee CKRecord.Reference value is always valid? By valid I mean the target CkRecord pointed by the CKRecord.Reference exists in the database.
Let's consider an example. Suppose there are two tables: Account and Transaction:
Account Table:
AccountNumber Currency Rate
------------- -------- ----
a1 USD 0.03
Transaction Table:
TransactionNumber AccountNumber Amount
----------------- ------------- ------
t1 a1 20
Now suppose user does the following:
User first deletes account a1 and its associated transactions t1 on device A. The device saves the change to cloud.
Then user adds a new transaction t2 to account a1 on device B, before the device receives the change made in step 1 from cloud. Since a1 hasn't been deleted on device B, the operation should succeed locally. The device tries to save the change to cloud too.
My questions:
Q1) Will device B be able to save the change in step 2 to cloud?
I hope it would fail, because otherwise it would lead to inconsistent data. But I find the following in CKModifyRecordsOperation doc (emphasis mine), which implies CloudKit allows invalid reference:
During a save operation, CloudKit requires that the target record of the parent reference, if set, exists in the database or is part of the same operation; all other reference fields are exempt from this requirement.
(BTW, I think the fact that, when using CloudKit, Core Data requires all relations must be optional also indicates that CloudKit can't guarantee relation is always valid, though I think that is mainly an issue on client side caused by data transfer size. The above example, however, is different in that it's an issue on cloud side - the data on cloud is inconsistent).
I also find the following in the document. However, I don't think it helps in the above example, because IIUC CloudKit can only detect conflict when the changes on the same record but the changes in step 1 and step 2 are on different records.
Because records can change between the time you fetch them and the time you save them, the save policy determines whether new changes overwrite existing changes. By default, the operation reports an error when there’s a newer version on the server.
If the above understanding is correct, however, I don't understand why the same document has the following requirement, which implies CloudKit doesn't allow invalid reference:
When creating two new records that have a reference between them, use the same operation to save both records at the same time.
Q2) Suppose CloudKit allows invalid reference on cloud side (that is, device B successfully saves the change in step 2 to cloud) , I wonder what's the best practice to deal with it?
I think the issue is different from the optional relation requirement in Core Data when using CloudKit, because in that case the data is consistent on cloud side and eventually the client will receive complete data. In the above example, however, the data on cloud is inconsistent so the client has to remedy it somehow (although client has little information helping it).
One approach I think of is to avoid the issue in the first place. My idea is to maintain a counter in the database and requires client to increase the counter (it's not Lamport clock. BTW, is it possible to use Lamport clock in this case?) when making any change. This should help CloudKit to detect conflict (though I can't think out a good strategy on how client should deal with it. A simple one is perhaps to prompt user to select one copy). However, this approach effectively uses cloud as a centralized server, which I suspect isn't the typical way how people use CloudKit, and it requires clients to maintain local counter value in various situations. I wonder what's the typical approach? Am I missing something?
Thanks for any help.
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
I'm wondering if there is a way to force a re-fetch of a @Query property inside of a SwiftUI view so I could offer a pull-to-refresh mechanism for users to force-refresh a view.
Why would I want this?
iOS 18.0 and 18.1 currently contain some regressions that prevent SwiftData from properly gathering model updates caused by ModelActor's running on background threads and the suggested workarounds (listening for .NSManagedObjectContextDidSave) don't work well in most scenarios and do not cause queries in the current view to be fully re-evaluated (see Importing Data into SwiftData in the Background Using ModelActor and @Query).
I have a project that currently has data saved locally and I'm trying to get it to sync over multiple devices.
Currently basic data is syncing perfectly fine, but I'm having issues getting the images to convert to data. From what I've researched it because I'm using a UIImage to convert and this caches the image
It works fine when there's only a few images, but if there's several its a pain
The associated code
func updateLocalImages() {
autoreleasepool {
let fetchRequest: NSFetchRequest<Project> = Project.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "converted = %d", false)
fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Project.statusOrder?.sortOrder, 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 pictures = project.pictures {
projectPicNumber = pictures.count
for pic in pictures {
currentPicNumber = currentPicNumber + 1
let picture : Picture = pic as! Picture
if let imgData = convertImage(picture: picture) {
picture.pictureData = imgData
}
}
project.converted = true
saveContext()
}
}
} catch {
print("Fetch Failed")
}
}
}
func convertImage(picture : Picture)-> Data? {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let path = paths[0]
if let picName = picture.pictureName {
let imagePath = path.appendingPathComponent(picName)
if let uiImage = UIImage(contentsOfFile: imagePath.path) {
if let imageData = uiImage.jpegData(compressionQuality: 0.5) {
return imageData
}
}
}
return nil
}```
Ive been getting this error on an app in the dev environment since iOS16. it continues to happen in the latest iOS release (iOS18).
After this error/warning, CoreData_CloudKit stops syncing and the only way to fix it is to delete the app from all devices, reset the CloudKit dev environment, reload the schema and reload all data. im afriad that if I ever go live and get this error in production there won't be a way to fix it given I cant go and reset the production CloudKit environment.
It doesn't happen straight away after launching my app in a predictable manner, it can take several weeks to happen.
Ive posted about this before here and haven't got a response. I also have a feedback assistant issue submitted in 2022 as part of ios16 beta that is still open: FB10392936 for a similar issue that caused the same error.
would like to submit a code level support query but it doest seem to have anything to do with my code - but rather the Apple core data CloudKit syncing mechanism.
anyone have any similar issues or a way forward?
> error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2200): <NSCloudKitMirroringDelegate: 0x301e884b0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringImportRequest: 0x3006f5a90> D823EEE6-EFAE-4AF7-AFED-4C9BA708703B' due to error: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x73, 0x61, 0x6d)" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x73, 0x61, 0x6d)}
I am trying to get my head around SwiftData, and specifically some more "advanced" ideas that I have not seen covered in the various tutorials.
Specifically, I have a class that includes a collection that may or may not contain elements. For now I am experimenting with a simple array of Date, and I don't know if I should make it an optional, or an empty array. Without SwiftData in the mix it seems like it's probably programmers choice, but I wonder if SwiftData handles those two scenarios differently, that would suggest one over the other.