In Xcode 15 beta 3 and iOS 17 beta 3, my app with SwiftData keeps generating error:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSManagedObject 0x2811cb390> setValue:forUndefinedKey:]: the entity dataSets is not key value coding-compliant for the key "(null)".'
I have a model:
@Model final class Station: Sendable {
...
var dataSets: [String]
}
The error seems to occur when saving entities of the model in SwiftData. There is no entity named "dataSets". Only a property in the above model. What's the null key in the error?
iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
Post
Replies
Boosts
Views
Activity
In a SwiftUI view it is easy to pull mainContext out of the Environment (thanks for that).
I have two questions:
(1) In Nick's code he shows:
let context = self.newSwiftContext(from: Trip.self)
can you say more about this method newSwiftContext(). How should we implement it to fetch a new context from the same container?
(2) In Core Data we usually read from the main context but write to a child of main context off the main thread and then the parent is notified it needs to refresh. How do we do that with SwiftData or is that managed for us?
Thanks,
Daniel
As of now, it's not listed as supported and also doesn't work.
Is SwiftData not coming to visionOS?
I'm curious to know if anyone has access to CloudKit in visionOS? I cannot find it anywhere. Least to mention, I cannot find CoreData/SwiftData either.
How has this impacted your ability to create next-gen apps, if you cannot deal with any kind of data storage/authentication/etc?
And does anyone have any idea when this will be available?
I'm testing the new SwiftData to see if I can use it on one of my apps. Specifically I'm trying to learn how to use the schema migrations.
I made a new project using Xcode 15 beta 4. I selected to use SwiftData and iCloud.
I ran the generated project and I added a couple of items to the screen.
Then, I wanted to make a schema migration, so I changed the Item model from:
@Model
final class Item {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
to also include a string title:
@Model
final class Item {
var timestamp: Date
var title: String
init(timestamp: Date, title: String) {
self.timestamp = timestamp
self.title = title
}
}
I also made some changes to the SwiftUI code to include an empty string when adding a new item, so it could compile:
let newItem = Item(timestamp: Date(), title: "")
And then I added a new file containing the migration, according to what I saw on the video sessions:
//
// SwiftDataMigrations.swift
// Test 1
//
// Created by Diego on 12/07/23.
//
import Foundation
import SwiftData
enum ItemSchemaV1: VersionedSchema {
static var versionIdentifier: String?
static var models: [any PersistentModel.Type] {
[Item.self]
}
@Model
final class Item {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
}
enum ItemSchemaV2: VersionedSchema {
static var versionIdentifier: String?
static var models: [any PersistentModel.Type] {
[Item.self]
}
@Model
final class Item {
var timestamp: Date
var title: String
init(timestamp: Date, title: String) {
self.timestamp = timestamp
self.title = title
}
}
}
enum ItemsMigrationPlan: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[ItemSchemaV1.self, ItemSchemaV2.self]
}
static var stages: [MigrationStage] {
[migrateV1toV2]
}
static let migrateV1toV2 = MigrationStage.lightweight(fromVersion: ItemSchemaV1.self, toVersion: ItemSchemaV2.self)
}
After that, I specified the migrationPlan in the app:
//
// Test_1App.swift
// Test 1
//
// Created by Diego on 12/07/23.
//
import SwiftUI
import SwiftData
@main
struct Test_1App: App {
var container = try! ModelContainer(
for: Item.self,
migrationPlan: ItemsMigrationPlan.self
)
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(container)
}
}
And then I tried to run the app but it crashed on launch with this error:
SwiftData/ModelContext.swift:179: Fatal error: Container does not have any data stores
Does anyone have any idea about what I might be missing?
The only thing that didn't matched the videos was that when creating a ModelContainer, the code on the video showed var container = ModelContainer... but the compiler showed the error Call can throw, but errors cannot be thrown out of a property initializer, so I added the try!. Also, on the VersionedSchema, I had to add static var versionIdentifier: String?.
Other than that I have no idea.
Thanks in advance.
Hello people,
I am currently experiencing a lot of disruption for the uploading of my files to the iCloud Drive. I have a folder that I share with some of my colleagues that contain some lectures notes and such, and I have two devices, a MacOS on the new Sonoma 14.0 Beta and an iPad on the 16.6 iPadOS. Recently the files started getting stuck upon upload and I think this started happening when I started sharing the folders with other people over iCloud.
I went through the internet multiple times to see if someone is having this problem and I willingly ran
sudo killall bird hoping it would fix my issue, but sadly it didn't.
Would appreciate any support on this, I am aware this might have a potential relation with the Beta MacOS.
How do I perform a search using SwiftData within an observable data model
For example: If I have a database of books that contains the property isbn, how would I perform a search to confirm I either had or did not have a book with the isbn I am searching for?
Using CoreData I use a fetch request:
let predicate = NSPredicate(format: "%K == %@", #keyPath(Book.isbn), isbn)
let fetchRequest: NSFetchRequest<Book> = Book.fetchRequest()
...
let book = try context.fetch(fetchRequest). // returns [book] use isEmpty for not found.
...
if book.isEmpty {
saveBook()
}
I have a number of queries I perform on the database to drive the logic within the app, this is just one example.
I cannot test at the moment, but have not found documentation on this yet. I don't have a sense of how ModelContainer works across targets.
I have not, for example, seen a project with SwiftData unit tests yet.
I'm using NSPersistentCloudKitContainer with my app and everything has been working fine for the most part. However, every now and then I come across an entity that saves fine into core data but then can't sync to cloud kit and causes the entire cloud kit feature to stop working. The error happens when starting the app and looks like this:
error: CoreData+CloudKit: -NSCloudKitMirroringDelegate _requestAbortedNotInitialized:: <NSCloudKitMirroringDelegate: 0x2820187e0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringImportRequest: 0x283a27930> 3CD51F2A-E632-4FF0-8B8C-C17DCB15A002' due to error: <CKError 0x281739a10: "Partial Failure" (2/1011); "Failed to modify some records"; uuid = 9C4B94E0-662F-4B75-894B-55AD51DE9C79; container ID = "iCloud.com.mrsdizzie.LaurasBooks"; partial errors: {
0A2C0554-254E-47AA-B2C5-58F6C1CA038E:(com.apple.coredata.cloudkit.share.164680EE-7664-4105-9039-2FA952A013AB:__defaultOwner__) = <CKError 0x28173a6a0: "Invalid Arguments" (12/2006); server message = "Cannot create or modify field 'CD_data_ckAsset' in record 'CD_ImageData' in production schema"; op = 065A25FC65E7BB30; uuid = 9C4B94E0-662F-4B75-894B-55AD51DE9C79>
... 3 "Batch Request Failed" CKError's omited ...
}>
The app is for keeping track of Books, so the basic data model is an entity named Book with a relationship named imageData. This maps to an entity named ImageData with a field named data. data is of type "binary data" and where the cover image for a particular book is stored. This has worked so far for hundreds of entries into core data and cloud kit, but every now and then I see an error like this in the console app and the only way to recover is delete the offending entry (either manually, or by removing the app which deletes all local data). I am now able to reproduce it with one particular entry on one device in production, but not sure how to proceed from there.
Since all of this syncing and creation of CKRecords happens automatically via NSPersistentCloudKitContainer I'm not really sure what to do, how to recover, or how to get more details about what it doesn't like in this particular case. I've monitored NSPersistentCloudKitContainer.eventNotificationUserInfoKey for event errors but only get short errors like:
CKError Domain: 2, Description: The operation couldn't be completed
The production schema is up to date and hasn't changed. Most entries into the app work fine. It is only every so often with certain entries that this error happens. There is no obvious difference between entries that I can see. The image itself in this and other cases is under 1MB.
Any advice appreciated. Thanks!
Hi all,
I am trying to render my SwiftUI views that uses SwiftData classes using sample data using the approach shown in the example code of wwdc2023-10196:
@MainActor #Preview {
TripsWidgetEntryView()
.modelContainer(PreviewSampleData.container)
}
Unfortunately this seems no longer valid.
Indeed I get this error:
I then tried to remove the @MainActor as suggested, but the error in then moved to another level:
What do you suggest to be the best approach to have back my preview working?
I am using Xcode Beta 4 - 15A5195m
Do you need to throw an Int into the model for this?
In CoreData, many-relationships are implemented as NSSet objects. In the SwiftData examples, they are shown as arrays. Are they really arrays (i.e., order-preserving and duplicates allowed) or are they arrays made from CoreData NSSets? In my applications, this makes a HUGE difference.
I'm working on a project that has the Core Data model in the Documents directory. There's a new app being built, which wants the model to be in the Application Support directory. How do I tell the app to use the Documents folder when loading the model? I've tried several things, like moving the model file, but nothing worked.
I've noticed when using @Model instead of @Observable that it bumps the CPU-usage of the app with 10%, since I'm reading values on every frame of render. This seems to cause a deep lookup. Is there a way to read the objects/attributes in memory somehow?
Trying to build an app that shares data across users, and one sanity check I was using was to check that the current user has granted permission to be looked up, and then I could display the user's name in the view. Previously, I could check the applicationPermissionStatus with CKContainer.applicationPermissionStatus(for:), and if it were not granted, I could request it with CKContainer.default().requestApplicationPermission. Both of those functions (and several others that i was using in my app) now pop up with the message: 'requestApplicationPermission' was deprecated in iOS 17.0: No longer supported. Please see Sharing CloudKit Data with Other iCloudUsers.
Unfortunately, I have found no alternate way to get the user identity in the Documentation, although it is a fairly large section and it's possible I am overlooking it. Is there a way to display the user's name components?
Hey,
I've been working with SwiftData for a while now and I'm currently in the process of adding iCloud functionality to my program. Everything works fine, but the data update only after running the app twice or restarting it twice in the simulator. It would be better if this could be done in real time or at the push of a button.
Does anyone have an idea how to implement this?
The devices send a message in the background (that there is an update) or? Can you access it somehow and the @Query update?
Imagine I have a game with new levels every day. Users play my game and their progress is saved in Core Data, which is then synchronized with CloudKit via NSPersistentCloudKitContainer.
Users' progress is about 500Kb for each level/day.
That's 5 Mb in 10 days. Or 182 Mb in a year.
If the user plays my game for a year, gets a new iPhone, and installs my app again — will the NSPersistentCloudKitContainer eventually download all 182 Mb of users' data!?
Anyone know the SwiftData equivalet of the CoreData lifecycle methods. and how do we override them or do something similar? eg:
awakeFromInsert()
willSave()
didSave()
willTurnIntoFault()
prepareForDeletion()
Hi,
say in my model I have members and each member optionally can have a relationship to a Club. So the relationship in the Member entity would be modelled like so:
@Relationship(.nullify, inverse: \Club.members) var club: Club?
Now I would like to fetch al Members with no Club relationship. I would assume that this would work with a predicate like this:
let noClubPred = #Predicate<Member> { member in
member.club == nil
}
Unfortunately this gives me the following error when compiling:
Generic parameter 'RHS' could not be inferred.
Has anybody an idea how to phrase this predicate correctly, or is this a beta issue and it should actually work?
Thank you!
Cheers, Michael
Checking if there’s a current approach to encrypting whole SQLite. There is one requirement to encrypt the SQLite DB. How can use SQLCipher with core data.