For an array only the last row is inserted where print shows the loop is processed
for index in 0..<model.dataTable!.rows.count {
let row = model.dataTable!.rows[index]
catagory.name = row["Catagory"] as! String
context.insert(catagory)
print(catagory.name)
}
tried a forced try?save() which didn't help
Thanks
Joel
SwiftData
RSS for tagSwiftData is an all-new framework for managing data within your apps. Models are described using regular Swift code, without the need for custom editors.
Posts under SwiftData tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I updated today at Xcode 16 beta 6, and my app using SwiftData on iOS 18 (beta 6) is getting now this new error when saving the model in the modelContext.
I don't understand if it is a regression introduced in the beta 6 or if it is enforced something that previously wasn't.
It seems to be always referred to the ID property, for example:
SwiftData/ModelCoders.swift:1762: Fatal error: Passed nil for a non-optional keypath \MyModel.id
In this case (and in most of the cases in my models) the ID is defined as following
@Attribute(.unique)
public var id: UUID
I also tried to add the initialization inline, but didn't help
@Attribute(.unique)
public var id: UUID = .init()
I also tried to remove the @Attribute(.unique), didn't help as well.
Does any of you have the same issue?
When changing a property of a SwiftData Model from a ModelActor the memory needed slightly increases. Once you do that more often, you can see that the usage is linearly increasing. I modified the Swiftdata template as little as possible. This is the least code I need to reproduce the problem:
Changes In the @main struct :
ContentView(modelContainer: sharedModelContainer)
ContentView:
struct ContentView: View {
@Query private var items: [Item]
let dataHanndler: DataHandler
@State var timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false, block: { t in })
var body: some View {
NavigationSplitView {
List {
ForEach(items) { item in
NavigationLink {
Text("Item at \(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))")
} label: {
Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
}
}
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
ToolbarItem {
Button {
timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { t in
Task {
await dataHanndler.updateRandom()
// Obviously this makes little sense but I need to update a lot of entities in my actual app. This is the simplest way to demonstrate that. updateRandom() could also be a function of a view but that doesn't make a difference
}
}
} label: {
Label("Do a lot of writing", systemImage: "gauge.with.dots.needle.100percent")
}
}
ToolbarItem {
Button {
timer.invalidate()
} label: {
Label("Invalidate", systemImage: "stop.circle")
}
}
}
} detail: {
Text("Select an item")
}
}
private func addItem() {
Task {
await dataHanndler.insert(timestamp: Date.now)
}
}
init(modelContainer: ModelContainer) {
self.dataHanndler = DataHandler(modelContainer: modelContainer)
}
}
ModelActor:
@ModelActor
actor DataHandler {
public func update<T>(_ persistentIdentifier: PersistentIdentifier, keypath: ReferenceWritableKeyPath<Item, T>, to value: T) throws {
let model = modelContext.model(for: persistentIdentifier) as! Item
model[keyPath: keypath] = value
}
public func insert(timestamp: Date) {
let item = Item(timestamp: timestamp)
modelContext.insert(item)
}
public func updateRandom() {
let count = try! modelContext.fetchCount(FetchDescriptor<Item>())
var descriptor = FetchDescriptor<Item>()
descriptor.fetchOffset = Int.random(in: 0..<count)
descriptor.fetchLimit = 1
let model = try! modelContext.fetch(descriptor)
model.first!.timestamp = Date.now
}
}
I filed a bug report FB14876920 but I am looking for other ideas to solve this before it will be fixed in a future update. The modelContext I use is created and managed by the @ModelActor macro.
Happy to hear ideas
I have SwiftData configured with CloudKit iCloud sync, and the sync is initiated only when the application is launched or the scene phase is changed. CloudKit remote notifications are not received while the application is running; instead, each sync remote notification is sent to app only upon a scene phase change, such as transitioning from the Home Screen to the Main Screen and returning. Subsequently, the application syncs with the most recent data. I have observed other individuals who have implemented a similar sync but with diffrent data, where a record is added on one device, and it appears on the other device without the need to change the scene phase. Currently, I am using two physical devices: a Mac and an iPhone. The Mac is running macOS 15.1 beta 2, while the iPhone is running iOS 18.0 beta 6 Xcode Version is 15.1.
CloudKit Sync Issue: CloudKit remote notifications to update data only appear when the app’s scene phase changes, not when the app is running.
Sync Trigger: To sync again, the scene phase needs to be changed to trigger the sync.
App uses @Query macro with different predicates like
@Query(filter: #Predicate<Payment>{ $0.isPinned && $0.renewalID != 1000 }, sort: \.pinnedOrder, animation: .smooth) private var paymentsData: [Payment]
@Query var data: [Payment] and the predicate is made in the initializer of the view.
init(searchText: String) {
self.searchText = searchText
let billsPredicate = #Predicate<Payment>{$0.renewalID != 1000 }
_bills = Query(filter: billsPredicate, animation: .smooth)
let pinnedPredicate = #Predicate<Payment>{
if searchText.isEmpty{
$0.isPinned && $0.renewalID != 1000
}else{
$0.isPinned && $0.renewalID != 1000 && $0.name.localizedStandardContains(searchText)
}
}
_pinnedBills = Query(filter: pinnedPredicate, sort: \.pinnedOrder, animation: .smooth)
let notPinnedPredicate = #Predicate<Payment>{
if searchText.isEmpty{
!$0.isPinned && $0.renewalID != 1000
}else{
!$0.isPinned && $0.renewalID != 1000 && $0.name.localizedStandardContains(searchText)
}
}
_notPinnedBills = Query(filter: notPinnedPredicate, sort: \.name, animation: .smooth)
}
*The application has minimal deployment targets set to iOS 17.0, macOS Sonoma 14.0, watchOS 10.0, and visions 1.1.
When I tested it I used two builds just compiled in Xcode or two builds downloaded from TestFlight
All CloudKit Container changes are deployed to production and app bundle id is like app.SomeApp and container id is iCloud.app.SomeApp
*I verified the functionality by adding a record on one device and observing it appearance on another device. Alternatively, I modified record details, such as the name, in the CloudKit Console and watch for changes without app restart. Every time scene phase is needed to trigger sync and see changes.
What actions can I take to ensure data synchronization or download occurs when the application is in use? (scenePhase is .active )
I have a model "Objetive" with recursive iteration. In the user interface I can see all the Items, as expected, and I can expands all those that have children. However, I encounter an error when attempting to compact anyone with children that I have previously expanded, But only when I'm using Mac OS 15.1 On iOS 18.1 Works perfectly.
The error happens in List, Outlinegroup or Table.
struct ObjectiveTable: View{
@Query(filter: #Predicate<Objective>{$0.parent == nil}) var all : [Objective]
@State var selected : Objective?
var body: some View{
VStack{
List(all ,children: \Objective.sonsNIL){ line in
Text(line.name)
}
}
}
}
@Model
final class Objective{
@Attribute(.unique)
var id = UUID()
var name: String
var parent: Objective? = nil
@Relationship(deleteRule: .cascade, inverse: \Objective.parent)
var sons: [Objective] = []
var sonsNIL: [Objective]?{
get{
if sons.count < 1{
return nil
} else{
return sons
}
}
}
...
ERROR
Row index -1 out of row range (numberOfRows: 14) for <SwiftUI.SwiftUIOutlineListView: 0x129852200>
(
0 CoreFoundation 0x000000018c834ec0 __exceptionPreprocess + 176
1 libobjc.A.dylib 0x000000018c31acd8 objc_exception_throw + 88
2 AppKit 0x00000001903eb304 -[NSTableRowData availableRowViewWhileUpdatingAtRow:] + 0
3 SwiftUI 0x00000001bb365224 $s7SwiftUI0A17UIOutlineListViewC11removeItems2at8inParent13withAnimationy10Foundation8IndexSetV_ypSgSo07NSTableeL7OptionsVtF + 1388
4 SwiftUI 0x00000001bb3656f8 $s7SwiftUI0A17UIOutlineListViewC11removeItems2at8inParent13withAnimationy10Foundation8IndexSetV_ypSgSo07NSTableeL7OptionsVtFTo + 252
5 CoreFoundation 0x000000018c7a28b4 invoking + 148
6 CoreFoundation 0x000000018c7a272c -[NSInvocation invoke] + 428
7 CoreFoundation 0x000000018c7d7958 -[NSInvocation invokeWithTarget:] + 64
8 AppKit 0x000000019052a110 -[NSObjectAnimator forwardInvocation:] + 1512
9 CoreFoundation 0x000000018c7a0ee4 forwarding + 964
10 CoreFoundation 0x000000018c7a0a60 CF_forwarding_prep_0 + 96
11 SwiftUI 0x00000001bb37e458 $s7SwiftUI22OutlineListCoordinatorC19recursivelyDiffRows_4with2by9expandAllyAA0a9UIOutlineD4ViewC_AA0dC4ItemCAA0nD4TreeVAA14ExpansionStateOtF + 37012
12 SwiftUI 0x00000001bb3802b8 $s7SwiftUI22OutlineListCoordinatorC19recursivelyDiffRows_4with2by9expandAllyAA0a9UIOutlineD4ViewC_AA0dC4ItemCAA0nD4TreeVAA14ExpansionStateOtF + 44788
13 SwiftUI 0x00000001bb37538c $s7SwiftUI22OutlineListCoordinatorC8diffRows2of2toyAA0a9UIOutlineD4ViewC_AA0kD4TreeVtF + 120
14 SwiftUI 0x00000001bb36f3d4 $s7SwiftUI22OutlineListCoordinatorC6update4diff04viewD4Tree18idSelectionChanged010navigationk4SeedL0011templateRowL011transactionySb_AA04ViewdI0VS3bAA11TransactionVtFyycfU_yyXEfU + 220
15 SwiftUI 0x00000001bb369044 $s7SwiftUI22OutlineListCoordinatorC24withSelectionUpdateGuard33_BE7B171B0BEE2A9E27ED12968C3771F8LLyySS_yyXEtF + 1320
16 SwiftUI 0x00000001bb36f2d4 $s7SwiftUI22OutlineListCoordinatorC6update4diff04viewD4Tree18idSelectionChanged010navigationk4SeedL0011templateRowL011transactionySb_AA04ViewdI0VS3bAA11TransactionVtFyycfU + 708
17 SwiftUICore 0x00000002277cb578 $sIeg_ytIegr_TRTA + 28
18 SwiftUICore 0x0000000227a6d2b8 $s7SwiftUI6UpdateO15dispatchActionsyyFZ + 1236
19 SwiftUICore 0x0000000227a6c79c $s7SwiftUI6UpdateO3endyyFZ + 212
20 SwiftUICore 0x0000000227f6061c $sSo9NSRunLoopC7SwiftUIE11addObserveryyyycFZySo05CFRunbF3RefaSg_So0gB8ActivityVSvSgtcfU_Tf4ddd_n + 176
21 CoreFoundation 0x000000018c7c17a8 CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 36
22 CoreFoundation 0x000000018c7c1694 __CFRunLoopDoObservers + 552
23 CoreFoundation 0x000000018c7c0380 CFRunLoopRunSpecific + 648
24 HIToolbox 0x0000000197c000cc RunCurrentEventLoopInMode + 292
25 HIToolbox 0x0000000197c05d1c ReceiveNextEventCommon + 220
26 HIToolbox 0x0000000197c06020 _BlockUntilNextEventMatchingListInModeWithFilter + 76
27 AppKit 0x0000000190303650 _DPSNextEvent + 660
28 AppKit 0x0000000190c2a408 -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 688
29 AppKit 0x00000001902f675c -[NSApplication run] + 480
30 AppKit 0x00000001902cd02c NSApplicationMain + 888
31 SwiftUI 0x00000001ba77045c $s7SwiftUI6runAppys5NeverOSo21NSApplicationDelegate_So11NSResponderCXcFTf4e_nAA07TestingdG0C_Tg5Tm + 160
32 SwiftUI 0x00000001babf4854 $s7SwiftUI6runAppys5NeverOxAA0D0RzlF + 84
33 SwiftUI 0x00000001baf04134 $s7SwiftUI3AppPAAE4mainyyFZ + 224
34 Marlo SystemManagement.debug.dylib 0x0000000100ce6130 $s22Marlo_SystemManagement0a1_bC3AppV5$mainyyFZ + 40
35 Marlo SystemManagement.debug.dylib 0x0000000100ce61fc __debug_main_executable_dylib_entry_point + 12
36 dyld 0x000000018c358274 start + 2840
)
FAULT: NSTableViewException: Row index -1 out of row range (numberOfRows: 14) for <SwiftUI.SwiftUIOutlineListView: 0x129852200>; (user info absent)
The central feature of my app requires the use of AttributedStrings with multiple custom attributes to store data about various functions related to parts of them. These AttributedString and other data also need to be persisted in SwiftData.
Regarding how to do this, I spoke with an Apple engineer during WWDC24, and he said this was possible with the use of a ValueTransformer. After looking into this, I decided upon this scheme (forward direction shown here): Transform the AttributedString (with its custom attributes) into JSON data and have this interpreted as NSData, which SwiftData can persist.
The value transformer seems to transform the AttributedString to NSData and back without any problems. But any attempts to use this transformer with SwiftData crashes the app.
Your prompt solution to this problem would be greatly appreciated.
[Submitted as FB14860454, but posting here since I rarely get responses in Feedback Assistant]
In a simple SwiftData app that adds items to a list, memory usage drastically increases as items are added. After a few hundred items, the UI lags and becomes unusable.
In comparison, a similar app built with CoreData shows only a slight memory increase in the same scenario and does NOT lag, even past 1,000 items.
In the SwiftData version, as each batch is added, memory spikes the same amount…or even increases! In the CoreData version, the increase with each batch gets smaller and smaller, so the memory curve levels off.
My Question
Are there any ways to improve the performance of adding items in SwiftData, or is it just not ready for prime time?
Example Projects
Here are the test projects on GitHub if you want to check it out yourself:
PerfSwiftData
PerfCoreData
Background
I have a SwiftData Model specified like this, within a SwiftUI app:
@Model
class MyModel
{
// Model information.
}
It's been working as expected. I can add it to my app's model container as follows:
WindowGroup
{
ContentView()
}
.modelContainer(for: [MyModel.self])
And have been able to create, persist, and fetch data as expected.
Problem
I created a function to delete the persisted data:
func deleteData(modelContext: ModelContext)
{
modelContext.delete(MyModel.self)
}
But the compiler is throwing this error:
Type 'MyModel.Type' cannot conform to 'PersistentModel'.
I'm attempting to do this based of the documentation which specifies that only a model may be provided to delete all instances:
Warning If you don’t provide a predicate, the context will remove all
models of the specified type from the persistent storage.
Other Information
Is this a bug in Xcode or the Swift compiler? It makes no sense at all, for the following reasons.
MyModel is explicitly PersistentModel
I can adjust my model to the following without any errors:
@Model
class MyModel: PersistentModel
{
// Model information.
}
So clearly MyModel does conform to PersistentModel, but it doesn't clear the error.
(Note: There are no compiler errors that pop up, but there actually will be a Preview error that says Redundant conformance of 'MyModel' to protocol 'PersistentModel', which is helpful as more confirmation that it conforms either way.)
.modelContainer(for:) accepts PersistentModel
I'm calling .modelContainer(for: [MyModel.self]) without any issues, and the documentation for this function confirms that it accepts a PersistentModel for parameter.
The documentation for ModelContainer has these initializers:
init(for: Schema, migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: [ModelConfiguration]) throws
convenience init(for: any PersistentModel.Type..., migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: ModelConfiguration...) throws
convenience init(for: Schema, migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: ModelConfiguration...) throws
One of them explicitly accepts any PersistentModel.Type, and the other two accept Schema, whose documentation shows the initializer that I seem to be using, which also accepts any PersistentModel.Type:
init([any PersistentModel.Type], version: Schema.Version)
Conclusion
Overall, it seems like this might be a bug since the class can be explicitly labeled as PersistentModel without errors, and it's already being used with functions that require a PersistentModel parameter.
What can I do about this?
I found this answer from about a year ago, but none of the solutions seem applicable. One of them mentions a bug that was supposedly fixed. I'm on Xcode 15.4.
So I have two class models, Item and Category, as follows:
@Model
class Category {
let name: String
...
}
@Model
class Item {
var name: String
var category: Category?
...
}
I have a view called ItemDetailsView that displays all the properties of a given item. It also has a toggle that shows an ItemEditorView where user's can edit the item properties, including the category which shows up in a picker.
I set up the preview for ItemDetailsView as follows:
#Preview {
let preview = Preview(Item.self, Category.self)
preview.addExamples(Category.sampleCategories)
preview.addExamples(Item.sampleItems)
return ItemDetailsView(item: Item.sampleItems[0])
.modelContainer(preview.container)
}
The Preview class sets up my model container and inserts the sample items and categories that I have instantiated as static constant variables.
struct Preview {
let container: ModelContainer
init(_ models: any PersistentModel.Type...) {
let schema = Schema(models)
let config = ModelConfiguration(isStoredInMemoryOnly: true)
do {
container = try ModelContainer(for: schema, configurations: config)
} catch {
fatalError("Could not create preview container")
}
}
func addExamples(_ examples: [any PersistentModel]) {
Task { @MainActor in
examples.forEach { example in
container.mainContext.insert(example)
}
}
}
}
I'm not sure why my preview is crashing. I had a hunch that it was because we needed all the categories to be available for the picker in ItemEditorView but I already inserted the relevant categories into the model context. Preview is working as expected in a different view called ItemDetailsView which lists all the items added. Navigation links and sheets work perfectly. Not sure why this is giving me trouble.
What is the correct usage of two modelContexts (when you have a main one for swiftUI, and a background one for background operations - like networking)?
Is it expected that when the main one make updates, that the background modelContexts would also update automatically?
And if it doesn't, is there a way to force it to get updates?
Xcode 16 beta 3
Assume a SwiftData model starts like this and has a few more properties like a name and creation date (these are immaterial to my main question.
@Model
final class Batch: Identifiable, Sendable {
@Attribute(.unique) var id: UUID
//... more stuff
The combination of Swift 6 (or Swift 5 with warnings enabled) and SwiftData seem to provide a paradox:
Swift 6 complains when the id is a let:
Cannot expand accessors on variable declared with 'let'; this is an error in the Swift 6 language mode
Swift 6 complains when the id is a var:
Stored property '_id' of 'Sendable'-conforming class 'Batch' is mutable; this is an error in the Swift 6 language mode
Removing "Sendable" may be one solution but defeats the purpose and causes warnings elsewhere in the app about the model not being Sendable.
Is there an obvious fix?
Am I as a newbie (to the combination of Swift 6 and SwiftData) missing an entire architectural step of using ModelActor somewhere?
Hi,
I'd like to prevent some model classes from CloudKit sync. They are not referenced from - aka have no relation to - the synced model objects. Is there an straightforward way to do this?
I'm currently managing two independent ModelContext instances in my app—one dedicated to CKSyncEngine and another for the Main/UI thread.
While this setup works to some extent, I'm encountering a couple of issues:
UI Updates: When SwiftData is updated via CKSyncEngine, the UI doesn't automatically refresh. To address this, I've had to implement .refreshable() and write imperative Swift code to (re)fetch data. This approach feels counterintuitive since it prevents me from fully leveraging SwiftUI's declarative nature, such as using @Query and user must explicitly trigger refresh.
Deletion Logic: If users delete data via the UI, I have to manage a different delete code path. Specifically, I need to ensure that the object is removed from the UI's ModelContext without triggering a deletion in CKSyncEngine's ModelContext. This dual-path deletion logic feels unnecessarily complex.
Also, I intend to later re-use CKSyncEngine part for Command Line tool app that will not have UI at all.
What is the correct way to manage SwiftData in a background process like CKSyncEngine while maintaining a seamless and declarative approach in SwiftUI?
I recently added SwiftData to my project in a limited capacity. I'm creating ModelConfiguration -> ModelContext directly in Swift code rather than in SwiftUI. I'm using an app group & a CloudKit database/container.
The functionality all seems fine, but I'm dealing with random 0xdead10cc crashes from threads with CoreData/libsqlite3.dylib in the stack traces (particularly with widgets & complications which aren't actively writing anything), often with NSCloudKitMirroringDelegate.m also in the stack. I haven't seen any actual functionality issues, but the crashing is worrisome.
I understand they're keeping files open to cause the 0xdead10cc, but my question is: Is there a clean way to shut down or force shut down SwiftData when using CloudKit? I've looked through example code on Apple's Developer site, but I can't seem to find anything about cleanup/shutdown best practices, though I may be missing something.
Here's an example thread from a crash log:
Thread 12:
0 libsystem_kernel.dylib 0x00000000258b4fe4 pread + 12
1 libsqlite3.dylib 0x0000000023ce7684 seekAndRead + 88 (sqlite3.c:44032)
2 libsqlite3.dylib 0x0000000023c5ffc4 unixRead + 200 (sqlite3.c:44124)
3 libsqlite3.dylib 0x0000000023c730fc readDbPage + 132 (sqlite3.c:66901)
4 libsqlite3.dylib 0x0000000023cf14e4 getPageNormal + 532 (sqlite3.c:69515)
5 libsqlite3.dylib 0x0000000023cfd684 getAndInitPage + 104 (sqlite3.c:79184)
6 libsqlite3.dylib 0x0000000023c8f99c moveToRoot + 532 (sqlite3.c:82309)
7 libsqlite3.dylib 0x0000000023cfa448 sqlite3BtreeTableMoveto + 168 (sqlite3.c:82547)
8 libsqlite3.dylib 0x0000000023c859fc sqlite3VdbeExec + 4996 (sqlite3.c:105391)
9 libsqlite3.dylib 0x0000000023c83da4 sqlite3_step + 976 (sqlite3.c:97868)
10 CoreData 0x00000000211c92d4 _execute + 128 (NSSQLiteConnection.m:4573)
11 CoreData 0x00000000211c5e74 -[NSSQLiteConnection execute] + 1784 (NSSQLiteConnection.m:5014)
12 CoreData 0x000000002121c3f8 -[NSSQLiteConnection insertRow:] + 1488 (NSSQLiteConnection.m:3608)
13 CoreData 0x00000000211ca160 _executeSaveChangesRequest + 1792 (NSSQLCore_Functions.m:2543)
14 CoreData 0x00000000211dc128 -[NSSQLSaveChangesRequestContext executeRequestCore:] + 28 (NSSQLSaveChangesRequestContext.m:263)
15 CoreData 0x00000000211fa424 -[NSSQLStoreRequestContext executeRequestUsingConnection:] + 220 (NSSQLStoreRequestContext.m:183)
16 CoreData 0x00000000211cce3c __52-[NSSQLDefaultConnectionManager handleStoreRequest:]_block_invoke + 56 (NSSQLConnectionManager.m:302)
17 CoreData 0x00000000211c99d4 __37-[NSSQLiteConnection performAndWait:]_block_invoke + 40 (NSSQLiteConnection.m:733)
18 libdispatch.dylib 0x0000000020af2b94 _dispatch_client_callout + 16 (object.m:576)
19 libdispatch.dylib 0x0000000020b004d8 _dispatch_lane_barrier_sync_invoke_and_complete + 56 (queue.c:1104)
20 CoreData 0x00000000211c3d4c -[NSSQLiteConnection performAndWait:] + 140 (NSSQLiteConnection.m:730)
21 CoreData 0x000000002122fb3c -[NSSQLDefaultConnectionManager handleStoreRequest:] + 208 (NSSQLConnectionManager.m:297)
22 CoreData 0x00000000211bd16c -[NSSQLCoreDispatchManager routeStoreRequest:] + 216 (NSSQLCoreDispatchManager.m:60)
23 CoreData 0x00000000211bfb8c -[NSSQLCore dispatchRequest:withRetries:] + 168 (NSSQLCore.m:3999)
24 CoreData 0x00000000211c0480 -[NSSQLCore executeRequest:withContext:error:] + 2044 (NSSQLCore.m:2963)
25 CoreData 0x000000002134662c __65-[NSPersistentStoreCoordinator executeRequest:withContext:error:]_block_invoke.387 + 8968 (NSPersistentStoreCoordinator.m:2967)
26 CoreData 0x00000000211c6190 -[NSPersistentStoreCoordinator _routeHeavyweightBlock:] + 220 (NSPersistentStoreCoordinator.m:644)
27 CoreData 0x00000000211bf3fc -[NSPersistentStoreCoordinator executeRequest:withContext:error:] + 1112 (NSPersistentStoreCoordinator.m:2779)
28 CoreData 0x00000000211d5468 -[NSManagedObjectContext save:] + 988 (NSManagedObjectContext.m:1624)
29 CoreData 0x0000000021296ba8 __52+[NSCKEvent beginEventForRequest:withMonitor:error:]_block_invoke_2 + 280 (NSCKEvent.m:76)
30 CoreData 0x00000000211d1024 developerSubmittedBlockToNSManagedObjectContextPerform + 156 (NSManagedObjectContext.m:3987)
31 libdispatch.dylib 0x0000000020af2b94 _dispatch_client_callout + 16 (object.m:576)
32 libdispatch.dylib 0x0000000020b004d8 _dispatch_lane_barrier_sync_invoke_and_complete + 56 (queue.c:1104)
33 CoreData 0x00000000211e3d8c -[NSManagedObjectContext performBlockAndWait:] + 256 (NSManagedObjectContext.m:4104)
34 CoreData 0x000000002129e14c __52+[NSCKEvent beginEventForRequest:withMonitor:error:]_block_invoke + 152 (NSCKEvent.m:66)
35 CoreData 0x00000000212231d0 -[PFCloudKitStoreMonitor performBlock:] + 84 (PFCloudKitStoreMonitor.m:148)
36 CoreData 0x0000000021284c28 +[NSCKEvent beginEventForRequest:withMonitor:error:] + 184 (NSCKEvent.m:61)
37 CoreData 0x000000002125fb80 __57-[NSCloudKitMirroringDelegate _performExportWithRequest:]_block_invoke + 256 (NSCloudKitMirroringDelegate.m:1435)
38 CoreData 0x0000000021209cb4 __92-[NSCloudKitMirroringDelegate _openTransactionWithLabel:assertionLabel:andExecuteWorkBlock:]_block_invoke + 64 (NSCloudKitMirroringDelegate.m:959)
39 libdispatch.dylib 0x0000000020af1288 _dispatch_call_block_and_release + 24 (init.c:1549)
40 libdispatch.dylib 0x0000000020af2b94 _dispatch_client_callout + 16 (object.m:576)
41 libdispatch.dylib 0x0000000020af96bc _dispatch_lane_serial_drain + 680 (queue.c:3934)
42 libdispatch.dylib 0x0000000020afa124 _dispatch_lane_invoke + 376 (queue.c:4025)
43 libdispatch.dylib 0x0000000020b03c40 _dispatch_root_queue_drain_deferred_wlh + 268 (queue.c:7193)
44 libdispatch.dylib 0x0000000020b034fc _dispatch_workloop_worker_thread + 516 (queue.c:6787)
45 libsystem_pthread.dylib 0x0000000025f9b7bc _pthread_wqthread + 280 (pthread.c:2696)
46 libsystem_pthread.dylib 0x0000000025f9b85c start_wqthread + 8 (:-1)
My app is crashing when one CloudKit device deletes a model instance and another opens a view that (used to) include reference to that instance.
Must I handle that case in my code? If so, how can I be notified before the rest of my code runs?
I am trying to count a database table from inside some of my classes.
I am tying to do this below **(My problem is that count1 is working, but count2 is not working.)
**
class AppState{
private(set) var context: ModelContext?
....
func setModelContext(_ context: ModelContext) {
self.context = context
}
@MainActor
func count()async{
let container1 = try ModelContainer(for: Item.self)
let descriptor = FetchDescriptor<Item>()
let count1 = try container1.mainContext.fetchCount(descriptor)
let count2 = try context.fetchCount(descriptor)
print("WORKING COUNT: \(count1)")
print("NOTWORKING COUNT: \(count2) -> always 0")
}
I am passing the context like:
...
@main
@MainActor
struct myApp: App {
@State private var appState = AppState()
@Environment(\.modelContext) private var modelContext
WindowGroup {
ItemView(appState: appState)
.task {
appState.setModelContext(modelContext)
}
}
.windowStyle(.plain)
.windowResizability(.contentSize)
.modelContainer(for: [Item.self, Category.self]) { result in
...
}
Can I get some guidance on why this is happening?
Which one is better to use?
If I should use count2, how can I fix it?
Is this the correct way to search inside an application using SwiftData ?
I don't wanna search using the View like @Query because this operation is gonna happen on the background of the app.
My app uses SwiftData and CloudKit to store and synchronize data. This works nice. in some scenarios, I need to listen to NSPersistentStoreRemoteChange event to deduplicate data.
In SwiftData, how do I get the persistentStoreCoordinator of the corresponding SwiftData ModelContainer? Or are there other APIs to achieve the same purpose? There is no relevant content in the developer documentation.
In addition, in wwdc 24, there is a new API to track history (https://developer.apple.com/cn/videos/play/wwdc2024/10075/). But there is no mention of how to listen to remote data change events either.
Hi, guys. When I update a value in a Core Data object, the view is not updated to show the change. I don't understand what I'm doing wrong, since this worked before. Right now I have Xcode 16 Beta installed, but it happens with Xcode 15. Here is an example.
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@State private var selectedItem: Item?
var body: some View {
NavigationStack {
VStack {
Text("Year: \(selectedItem?.year ?? 0)")
.onTapGesture {
changeYear()
}
Spacer()
}
.onAppear {
// Load an item from the database
let request: NSFetchRequest<Item> = Item.fetchRequest()
request.fetchLimit = 1
if let item = try? viewContext.fetch(request).first {
selectedItem = item
}
}
}
}
private func changeYear() {
let year = Int16.random(in: 1900..<2020)
print("Random year: \(year)")
selectedItem?.year = year
try? viewContext.save()
}
}
#Preview {
ContentView()
.environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
I think it is easy to follow. There is an entity called Item with an attribute called year. I preloaded a few objects for the preview. This view loads one item and assigns it to a state property. When you tap on the Text view, the changeYear() method is executed. In this method I select a random year, assign it to the object in the selectedItem property and save the context. A message is printed on the console with the new value, but the view never updates. I'm also having similar problems with SwiftData and To Many relationships. They also do not update the views when they are modified.
In case you want to test it, you can just create a new project with Core Data set in, change the name of the attribute in the Item entity to year and select Int16 as the data type, and then update the following method to preload some values.
@MainActor
static let preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
for _ in 0..<10 {
let newItem = Item(context: viewContext)
newItem.year = Int16.random(in: 1900..<2020)
}
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
return result
}()
Thanks for any help.
I get this error :
ModelContainer creation failed: SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer, _explanation: nil)
AbsGod/AbsGodApp.swift:25: Fatal error: Failed to create ModelContainer: The operation couldn’t be completed. (SwiftData.SwiftDataError error 1.)
when doing:
struct MyAppApp: App {
let container: ModelContainer
init() {
do {
let schema = Schema([
Workout.self,
Exercise.self
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
container = try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
print("ModelContainer creation failed: \(error)")
fatalError("Failed to create ModelContainer: \(error.localizedDescription)")
}
}
var body: some Scene {
WindowGroup {
TabBarView()
.tint(.red)
}
.modelContainer(for: [Workout.self, Exercise.self])
}
And I have no clue of how to resolve that. I saw similar issues with CloudKit, but I don't even have enabled it, just ticked Automatically manage signing in Signing & Capabilities of my project.
the relationship of my classes are defined like this, in a workout class having an array of exercises:
@Relationship(deleteRule: .cascade, inverse: \Exercise.workout) var exercises: [Exercise]? = []
and the inverse in the exercise class:
var workout: Workout?
I don't feel like the problem is coming from my classes, because when I try to reproduce the error on simpler project, everything works. it just won't create a modelContainder in my project and I have no idea what can makes that and the error is not really explicit...
Hello everyone,
I am currently developing an app using SwiftUI and SwiftData. In my app, I need to store about three photos per entry. But as the number of entries grows, I run into significant performance issues, especially with RAM and CPU utilization. The app slows down as the dataset grows.
I'm wondering what would be the best approach to deal with this. Should I continue to store the photos locally using SwiftData, or would it be better to upload them to a server (like AWS S3 or Firebase Storage) and store only the URLs in SwiftData?
I also want to implement caching to improve performance, what would be the best methods or practices for caching these images?
I would be very grateful for any advice or suggestions from the community.
Thank you in advance!