After Xcode 26.1 was updated and installing the OS 26.1 simulators, my app started crashing related to transformable properties. When I checked my schema, I noticed that properties with array collection types are suddenly set with an option transformable with Optional("NSSecureUnarchiveFromData")], even though I do not use any transformable types. I verified the macros, no transformable was specified. This is causing ModelCoders to encode/decode my properties incorrectly.
This is not an issue when I switch back to OS 26.0 simulators.
Core Data
RSS for tagSave your application’s permanent data for offline use, cache temporary data, and add undo functionality to your app on a single device using Core Data.
Posts under Core Data tag
94 Posts
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hello,
the last days I was trying to solve a bug in my Unit Tests related to the CoreData "NSManagedObjectContextObjectsDidChange" Notification.
Im using some kind of Notification handler to save and abstract that for the UI and while the tests are running this notification was triggered with objects that doesn't exists anymore, which has resulted in a crash.
After some debugging I have detected, that the objects in here are really old. The objects here was from few tests ago, where a Merge Conflict happened. In the meantime there was a plenty of resets and deletes of the whole db. I have also seen that the bad notification is the first in the stack trace of the main thread, which is in my opinion also not usual.
So the real question is:
The only difference what I have found for the bad notification to the real notification, was the existence of the key "NSObjectsChangedByMergeChangesKey" in the UserInfo dictionary of the ObjectsDidChange Notification. But this key is nowhere found in the documentation of Apple. Also the search engines does not produce any result. So what is this key and when is this key contained in this notification and when not?
Maybe if I understand this, it helps me to understand the overall issue ...
I have been using the basic NSPersistentContainer with 100k+ records for a while now with no issues. The database size can fluctuate a bit but on average it takes up about 22mb on device.
When I switch the container to NSPersistentCloudKitContainer, I see a massive increase in size to ~150mb initially. As the sync engine uploads records to iCloud it has ballooned to over 600mb on device. On top of that, the user's iCloud usage in settings reports that it takes up 1.7gb in the cloud.
I understand new tables are added and history tracking is enabled but the size increase seems a bit drastic. I'm not sure how we got from 22mb to 1.7gb with the exact same data.
A few other things that are important to note:
I import all the 100k+ records at once when testing the different containers. At the time of the initial import there is only 1 relation (an import group record) that all the records are attached to.
I save the background context only once after all the records and the import group have been made and added to the context.
After the initial import, some of these records may have a few new relations added to them over time. I suppose this could be causing some of the size increase, but its only about 20,000 records that are updated.
None of the records include files/ large binary data.
Most of the attributes are encrypted.
I'm syncing to the dev iCloud environment.
When I do make a change to a single attribute in a record, CloudKit reports that every attribute has been modified (not sure if this is normal or not )
Also, When syncing to a new device, the sync can take hours - days. I'm guessing it's having to sync both the new records and the changes, but it exponentially gets slower as more records are downloaded. The console will show syncing activity, but new records are being added at a slower rate as more records are added. After about 50k records, it grinds to a halt and while the console still shows sync activity, only about 100 records are added every hour.
All this to say i'm very confused where these issues are coming from. I'm sure its a combination of how i've setup my code and the vast record count, record history, etc.
If anyone has any ideas it would be much appreciated.
Hi there! I'm making an app that stores data for the user's profile in SwiftData. I was originally going to use UserDefaults but I thought SwiftData could save Images natively but this is not true so I really could switch back to UserDefaults and save images as Data but I'd like to try to get this to work first. So essentially I have textfields and I save the values of them through a class allProfileData. Here's the code for that:
import SwiftData
import SwiftUI
@Model
class allProfileData {
var profileImageData: Data?
var email: String
var bio: String
var username: String
var profileImage: Image {
if let data = profileImageData,
let uiImage = UIImage(data: data) {
return Image(uiImage: uiImage)
} else {
return Image("DefaultProfile")
}
}
init(email:String, profileImageData: Data?, bio: String, username:String) {
self.profileImageData = profileImageData
self.email = email
self.bio = bio
self.username = username
}
}
To save this I create a new class (I think, I'm new) and save it through ModelContext
import SwiftUI
import SwiftData
struct CreateAccountView: View {
@Query var profiledata: [allProfileData]
@Environment(\.modelContext) private var modelContext
let newData = allProfileData(email: "", profileImageData: nil, bio: "", username: "")
var body: some View {
Button("Button") {
newData.email = email
modelContext.insert(newData)
try? modelContext.save()
print(newData.email)
}
}
}
To fetch the data, I originally thought that @Query would fetch that data but I saw that it fetches it asynchronously so I attempted to manually fetch it, but they both fetched nothing
import SwiftData
import SwiftUI
@Query var profiledata: [allProfileData]
@Environment(\.modelContext) private var modelContext
let fetchRequest = FetchDescriptor<allProfileData>()
let fetchedData = try? modelContext.fetch(fetchRequest)
print("Fetched count: \(fetchedData?.count ?? 0)")
if let imageData = profiledata.first?.profileImageData,
let uiImage = UIImage(data: imageData) {
profileImage = Image(uiImage: uiImage)
} else {
profileImage = Image("DefaultProfile")
}
No errors. Thanks in advance
Some users of my app are reporting total loss of data while using the app.
This is happening specifically when they enable iCloud sync.
I am doing following
private func setupContainer(enableICloud: Bool) {
container = NSPersistentCloudKitContainer(name: "")
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
guard let description: NSPersistentStoreDescription = container.persistentStoreDescriptions.first else {
fatalError()
}
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
if enableICloud == false {
description.cloudKitContainerOptions = nil
}
container.loadPersistentStores { description, error in
if let error {
// Handle error
}
}
}
When user clicks on Toggle to enable/disable iCloud sync I just set the description.cloudKitContainerOptions to nil and then user is asked to restart the app.
Apart from that I periodically run the clear history
func deleteTransactionHistory() {
let sevenDaysAgo = Calendar.current.date(byAdding: .day, value: -7, to: Date())!
let purgeHistoryRequest = NSPersistentHistoryChangeRequest.deleteHistory(before: sevenDaysAgo)
let backgroundContext = container.newBackgroundContext()
backgroundContext.performAndWait {
try! backgroundContext.execute(purgeHistoryRequest)
}
}
I'm experiencing a critical issue with SwiftData custom migrations where objects created during migration appear to be inserted successfully but aren't persisted or found by queries after migration completes. The migration logs show objects being created, but subsequent queries return zero results.
I'm migrating from schema version V2 to V2_5, which involves:
Renaming Person class to GroupData
Keeping the same data structure but changing the class name while keeping the old class.
Using a custom migration stage to copy data from old to new schema
Below is an extract of my two schema and migration plan:
Environment:
Xcode 16.0,
iOS 18.0,
Swift 6.0
SchemaV2
enum LinkMapV2: VersionedSchema {
static let versionIdentifier: Schema.Version = .init(2, 0, 0)
static var models: [any PersistentModel.Type] {
[AnnotationData.self, Person.self, History.self]
}
@Model
final class Person {
@Attribute(.unique) var id: UUID
var name: String
var photo: String
var requirement: String
var statue: Bool
var annotationId: UUID?
var number: Int = 0
init(id: UUID = UUID(), name: String = "", photo: String = "", requirement: String = "", status: Bool = false, annotationId: UUID? = nil, number: Int = 0) {
self.id = id
self.name = name
self.photo = photo
self.requirement = requirement
self.statue = status
self.annotationId = annotationId
self.number = number
}
}
}
Schema V2_5
static let versionIdentifier: Schema.Version = .init(2, 5, 0)
static var models: [any PersistentModel.Type] {
[AnnotationData.self, Person.self, GroupData.self, History.self]
}
// Keep the old Person model for migration
@Model
final class Person {
@Attribute(.unique) var id: UUID
var name: String
var photo: String
var requirement: String
var statue: Bool
var annotationId: UUID?
var number: Int = 0
init(id: UUID = UUID(), name: String = "", photo: String = "", requirement: String = "", status: Bool = false, annotationId: UUID? = nil, number: Int = 0) {
self.id = id
self.name = name
self.photo = photo
self.requirement = requirement
self.statue = status
self.annotationId = annotationId
self.number = number
}
}
// Add the new GroupData model that mirrors Person
@Model
final class GroupData {
@Attribute(.unique) var id: UUID
var name: String
var photo: String
var requirement: String
var status: Bool
var annotationId: UUID?
var number: Int = 0
init(id: UUID = UUID(), name: String = "", photo: String = "", requirement: String = "", status: Bool = false, annotationId: UUID? = nil, number: Int = 0) {
self.id = id
self.name = name
self.photo = photo
self.requirement = requirement
self.status = status
self.annotationId = annotationId
self.number = number
}
}
}
Migration Plan
static let migrationV2toV2_5 = MigrationStage.custom(
fromVersion: LinkMapV2.self,
toVersion: LinkMapV2_5.self,
willMigrate: { context in
do {
let persons = try context.fetch(FetchDescriptor<LinkMapV2.Person>())
print("=== MIGRATION STARTED ===")
print("Found \(persons.count) Person objects to migrate")
guard !persons.isEmpty else {
print("No Person data requires migration")
return
}
for person in persons {
print("Migrating Person: '\(person.name)' with ID: \(person.id)")
let newGroup = LinkMapV2_5.GroupData(
id: person.id, // Keep the same ID
name: person.name,
photo: person.photo,
requirement: person.requirement,
status: person.statue,
annotationId: person.annotationId,
number: person.number
)
context.insert(newGroup)
print("Inserted new GroupData: '\(newGroup.name)'")
// Don't delete the old Person yet to avoid issues
// context.delete(person)
}
try context.save()
print("=== MIGRATION COMPLETED ===")
print("Successfully migrated \(persons.count) Person objects to GroupData")
} catch {
print("=== MIGRATION ERROR ===")
print("Migration failed with error: \(error)")
}
},
didMigrate: { context in
do {
// Verify migration in didMigrate phase
let groups = try context.fetch(FetchDescriptor<LinkMapV2_5.GroupData>())
let oldPersons = try context.fetch(FetchDescriptor<LinkMapV2_5.Person>())
print("=== MIGRATION VERIFICATION ===")
print("New GroupData count: \(groups.count)")
print("Remaining Person count: \(oldPersons.count)")
// Now delete the old Person objects
for person in oldPersons {
context.delete(person)
}
if !oldPersons.isEmpty {
try context.save()
print("Cleaned up \(oldPersons.count) old Person objects")
}
// Print all migrated groups for debugging
for group in groups {
print("Migrated Group: '\(group.name)', Status: \(group.status), Number: \(group.number)")
}
} catch {
print("Migration verification error: \(error)")
}
}
)
And I've attached console output below:
Console Output
I am using SwiftData for my model. Until Xcode 15 beta 4 I did not have issues. Since beta 5 I am receiving the following red warning multiple times:
'NSKeyedUnarchiveFromData' should not be used to for un-archiving and will be removed in a future release
This seems to be a CoreData warning. However, I am not using CoreData directly. I have no way to change the config of CoreData as used by SwiftData.
My model just uses UUID, Int, String, Double, some of them as optionals or Arrays. I only use one attribute (.unique).
It seems to me that NSStagedMigrationManager has algorithmic issues. It doesn't perform staged migration, if all its stages are NSLightweightMigrationStage.
You can try it yourself. There is a test project with three model versions V1, V2, V3, V4. Migrating V1->V2 is compatible with lightweight migration, V2->V3, V3->V4 is also compatible, but V1->V3 is not. I have following output:
Migrating V1->V2, error: nil
Migrating V2->V3, error: nil
Migrating V3->V4, error: nil
Migrating V1->V3, no manager, error: Optional("Persistent store migration failed, missing mapping model.")
Migrating V1->V3, lightweight[1, 2, 3], error: Optional("Persistent store migration failed, missing mapping model.")
Migrating V1->V3, lightweight[1]->lightweight[2]->lightweight[3], error: Optional("Persistent store migration failed, missing mapping model.")
Migrating V1->V3, custom[1->2]->lightweight[3], error: nil
Migrating V1->V3, lightweight[1]->custom[2->3], error: nil
Migrating V1->V3, custom[1->2]->custom[2->3], error: nil
Migrating V1->V4, error: Optional("Persistent store migration failed, missing mapping model.")
Migrating V2->V4, error: nil
Migrating V1->V4, custom[1->2]->lightweight[3, 4], error: nil
Migrating V1->V4, lightweight[3, 4]->custom[1->2], error: Optional("A store file cannot be migrated backwards with staged migration.")
Migrating V1->V4, lightweight[1, 2]->lightweight[3, 4], error: Optional("Persistent store migration failed, missing mapping model.")
Migrating V1->V4, lightweight[1]->custom[2->3]->lightweight[4], error: nil
Migrating V1->V4, lightweight[1,4]->custom[2->3], error: nil
Migrating V1->V4, custom[2->3]->lightweight[1,4], error: Optional("Persistent store migration failed, missing mapping model.")
I think that staged migration should satisfy the following rules for two consecutive stages:
Any version of lightweight stage to any version of lightweight stage;
Any version of lightweight stage to current version of custom stage;
Next version of custom stage to any version of lightweight stage;
Next version of custom stage to current version of custom stage.
However, rule 1 doesn't work, because migration manager skips intermediate versions if they are inside lightweight stages, even different ones.
Note that lightweight[3, 4]->custom[1->2] doesn't work, lightweight[1,4]->custom[2->3] works, but custom[2->3]->lightweight[1,4] doesn't work again.
Would like to hear your opinion on that, especially, from Core Data team, if possible.
Thanks!
Hello Apple Team,
We’re building a CloudKit-enabled Core Data app and would like clarification on the behavior and performance characteristics of Binary Data attributes with “Allows External Storage” enabled when used with NSPersistentCloudKitContainer.
Initially, we tried storing image files manually on disk and only saving the metadata (file URLs, dimensions, etc.) in Core Data. While this approach reduced the size of the Core Data store, it introduced instability after app updates and broke sync between devices. We would prefer to use the official Apple-recommended method and have Core Data manage image storage and CloudKit syncing natively.
Specifically, we’d appreciate guidance on the following:
When a Binary Data attribute is marked as “Allows External Storage”, large image files are stored as separate files on device rather than inline in the SQLite store.
How effective is this mechanism in keeping the Core Data store size small on device?
Are there any recommended size thresholds or known limits for how many externally stored blobs can safely be managed this way?
How are these externally stored files handled during CloudKit sync?
Does each externally stored Binary Data attribute get mirrored to CloudKit as a CKAsset?
Does external storage reduce the sync payload size or network usage, or is the full binary data still uploaded/downloaded as part of the CKAsset?
Are there any bandwidth implications for users syncing via their private CloudKit database, versus developer costs in the public CloudKit database?
Is there any difference in CloudKit or Core Data behavior when a Binary Data attribute is managed this way versus manually storing image URLs and handling the file separately on disk?
Our goal is to store user-generated images efficiently and safely sync them via CloudKit, without incurring excessive local database bloat or CloudKit network overhead.
Any detailed guidance or internal performance considerations would be greatly appreciated.
Thank you,
Paul Barry
Founder & Lead Developer — Boat Buddy / Vessel Buddy iOS App
Archipelago Environmental Solutions Inc.
I'm running a project with these settings:
Default Actor Isolation: MainActor
Approachable Concurrency: Yes
Strict Concurrency Checking: Complete (this issue does not appear on the other two modes)
I receive a warning for this very simple use case. Can I actually fix anything about this or is this a case of Core Data not being entirely ready for this?
In reference to this, there was a workaround listed in the release notes of iOS 26 beta 5 (https://forums.swift.org/t/defaultisolation-mainactor-and-core-data-background-tasks/80569/22). Does this still apply as the only fix for this?
This is a simplified sample meant to run on a background context. The issue obviously goes away if this function would just run on the MainActor, then I can remove the perform block entirely.
class DataHandler {
func createItem() async {
let context = ...
await context.perform {
let newGame = Item(context: context)
/// Main actor-isolated property 'timestamp' can not be mutated from a Sendable closure
newGame.timestamp = Date.now
// ...
}
}
}
The complete use case would be more like this:
nonisolated
struct DataHandler {
@concurrent
func saveItem() async throws {
let context = await PersistenceController.shared.container.newBackgroundContext()
try await context.perform {
let newGame = Item(context: context)
newGame.timestamp = Date.now
try context.save()
}
}
}
I'm trying to set up an application using SwiftData to have a number of models backed by a local datastore that's not synced to CloudKit, and another set of models that is. I was able to achieve this previously with Core Data using multiple NSPersistentStoreDescription instances.
The set up code looks something like:
do {
let fullSchema = Schema([
UnsyncedModel.self,
SyncedModel.self,
])
let localSchema = Schema([UnsyncedModel.self])
let localConfig = ModelConfiguration(schema: localSchema, cloudKitDatabase: .none)
let remoteSchema = Schema([SyncedModel.self])
let remoteConfig = ModelConfiguration(schema: remoteSchema, cloudKitDatabase: .automatic)
container = try ModelContainer(for: fullSchema, configurations: localConfig, remoteConfig)
} catch {
fatalError("Failed to configure SwiftData container.")
}
However, it doesn't seem to work as expected. If I remove the synced/remote schema and configuration then everything works fine, but the moment I add in the remote schema and configuration I get various different application crashes. Some examples below:
A Core Data error occurred." UserInfo={Reason=Entity named:... not found for relationship named:...,
Fatal error: Failed to identify a store that can hold instances of SwiftData._KKMDBackingData<...>
Has anyone ever been able to get a similar setup to work using SwiftData?
I have an app that has a Core Data store for dates with descriptions that I'd like to present in a widget with countdown calculations. In the app I have a button that just equates an active calculation to the currently selected item in the database (using an EnvironmentObject). I gather I can't use this mechanism inside a widget, right?
The user could put tons of items into the database - so I'm sure I don't want to have an editable widget allowing them to pick. I suppose I could create an intent and allow an independent entering from the app - but that seems rather user hostile since they've already entered it for the app - and I'm still trying to support iOS15 which doesn't support that.
I did create an App Group and have the Core Data store available from within the widget, but I don't see how to allow the user to choose which date is active. I also want multiple widgets to be able to point to different dates. Any help would be appreciated. Thanks!
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'm having an issue where FetchRequest does not consistently reflect changes that are made in the CoreData model. Things seem to work fine if you create or delete any object before editing, but if you only edit an object, the changes will not be shown.
Here is a minimal repro:
https://github.com/literalpie/fetchrequest-bug/tree/main
I have a workaround that involved adding a "noop" predicate that gets toggled whenever objectWillChange is emitted. This seems to force the FetchRequest to re-look at things.
.onReceive(items.publisher.flatMap(\.objectWillChange), perform: { _ in
items.nsPredicate = update ? NSPredicate(value: true) : NSPredicate(format: "1 == 1")
update.toggle()
})
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 am experiencing an issue where XCode reverts .xccurrentversion file in my iOS app to the first version whenever xcodebuild is run or whenever XCode is started. This means I can build the app and run tests in XCode if I discard the reversion .xccurrentversion on XCode start. However, testing on CI is impossible because the version the tests rely on are reverted whenever xcodebuild is run.
The commands I run to reproduce the issue
❯ git status
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: Path/.xccurrentversion
no changes added to commit (use "git add" and/or "git commit -a")
❯ git checkout "Path/.xccurrentversion"
Updated 1 path from the index
❯ git status
nothing to commit, working tree clean
❯ xcodebuild \
-scheme Scheme \
-configuration Configuration \
-sdk iphonesimulator \
-destination 'platform=iOS Simulator,name=iPhone 16 Pro,OS=latest' \
-skipPackagePluginValidation \
-skipMacroValidation \
test > /dev/null # test fails because model version is reverted
❯ git status
HEAD detached at pull/249/merge
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: Path/.xccurrentversion
no changes added to commit (use "git add" and/or "git commit -a")
I have experienced such issue in 16.3 (16E140) and 16.2 (16C5032a).
Similar issues/solutions I have found online are the following. But they are either not relevant or do not work in my case.
https://stackoverflow.com/questions/17631587/xcode-modifies-current-coredata-model-version-at-every-launch
https://github.com/CocoaPods/Xcodeproj/issues/81
Is anyone aware of any solution? Is there a recommended way I can run diagnostics on XCode and file a feedback?
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 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????
Hello guys,
this is my first post to this forum and really hope that somebody can help me here.
I would highly appreciate every help!
I am writing my first app with Swift UI (never used UIKit before) which I want to publish later on.
This is also my first app which has CoreData implemented.
For example I use the following entities:
Family, Person
1 Persons can have 1 Family
1 Family can have many Persons
My App is structured as the following:
ContentView:
Contains a TabView with 2 other views in it. A Settings View and a View with a LazyVGrid.
LazyVGrid View:
This View shows a GridItem for every Family. I get the Families with the following Fetchrequest:
@Environment(\.managedObjectContext) private var viewContext
// These are the Families from the FetchRequest
@FetchRequest(entity: Family.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Family.created, ascending: false)]
) var families: FetchedResults<Family>
Every GridItem is linking to a "FamilyDetailView" via NavigationLink. So i pass the family as the following:
NavigationLink(destination: FamilyDetailView(family: family).environment(\.managedObjectContext, self.viewContext), label: {Text("Family Name")
In the FamilyDetailView i get the Family with a property wrapper:
@State var family : Family
In this FamilyDetailView is the problem i have.
Here I also have a LazyVGrid, which shows 1 NavigationLink for every Person in the Family in a GridItem . In this GridItem I also show for example the "name" of the Person.
When tapping the NavigationLink i get to the last View, the PersonDetailView. This View gets the Person which is also an entity which has a relationship to the Family Entity.
I pass it as the follow:
NavigationLink(
destination: PersonDetailView(person: person),
label: {Text("Person")})
In the PersonDetailView I now change the name of the person and save the changed to CoreData.
The change is saved without a problem, the problem is that when I go back, using the topleading back button from the NavigationView, the Views are not updated. I have to restart the App to see the changes..
I know that the Problem has to be with passing the Data, but I cant figuring out what I did wrong.
I really appreciate everyone trying to help me!
Thank you very very much!!
我正在使用 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 实体并允许保存?
任何帮助或指导将不胜感激。