My code to show a list from a fetch that can be selected is (simplified) as follows
@FetchRequest(sortDescriptors: []) private var players: FetchedResults<PlayerEntity>
@State private var selectedPlayerID : PlayerEntity.ID?
var body: some View {
NavigationSplitView {
List(players, selection: $selectedPlayerID) { player in
Text(player.shortName ?? "")
}
.navigationTitle("Players")
} detail: {
if let id = selectedPlayerID, let player = players.first(where: {$0.id == id}) {
Text("Do Something")
}
}
}
I'm using the state variable of type ID PlayerEntity.ID? to hold the selection.
However, I noticed the sample app from migrating to SwiftData ("SampleTrips") is essentially doing it like this:
@FetchRequest(sortDescriptors: [SortDescriptor(\.startDate)])
private var trips: FetchedResults<Trip>
@State private var showAddTrip = false
@State private var selection: Trip?
@State private var path: [Trip] = []
var body: some View {
NavigationSplitView {
List(selection: $selection) {
ForEach(trips) { trip in
TripListItem(trip: trip)
//... removed some extra code
}
}
//... removed some extra code
.navigationTitle("Upcoming Trips")
//... removed some extra code
} detail: {
if let selection = selection {
NavigationStack {
TripDetailView(trip: selection)
}
}
}
The sample code is able to pass an optional managed object type Trip? to hold the selection rather than the ID type. When I try to replicate that behavior, I can't. Does anyone know what would be different?
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
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I need some help understanding how the public database works in CloudKit. First of all, let me say that I know how to connect and use the private database. In this question I'm not looking for an answer on how to connect to the database at self, only the concept. Here is my confusion. I have a set of images that all users in my app will be using, right now what I'm doing is adding the images directly to the app (an Image Set in Xcode) and then I am pulling them to Core Data and then syncing them to CloudKit. As you can see all images are technically stored in every device using my app and in Core Data/CloudKit, not very efficient. What I would like is to have the images stored in a single place where all uses can pull the images from, in this case CloudKit. I know I can have them somewhere in a private server, but I feel like I would be adding more complexity to my app, so I think using CloudKit is a better option for me. Here is my question.
How do I get the images to CloudKit, do I upload them directly to CloudKit and then read from all devices or do I need to first add them to a device and upload to CloudKit from there?
Thanks!
Hello. I had some problems related to objectID, let me try to describe it.
I had 3 managed object contexts:
context A - root private context of persistentCoordiantor, used for write changes to persistentStore. retainsRegisteredObjects = false
context B - main context, parent context - A. retainsRegisteredObjects = true
context C - background private context. parent context - B. retainsRegisteredObjects = true
When I add new MO to coreData, it saved succesfully to all contexts , but, when I check registeredObjects of context B and C, objectID for new MO is temporary, this is problem for me, because I had some work with coreData from NotificationServiceExtension, and I use fetch persistent history to get updates that was made in NSE and apply them to main app, but, in fetch history I get changes for MO that have permanentID, but in my context B and C there is still temporaryID. It was strange for me, so, I set retainsRegisteredObjects to context A, after that, I noticed, that after save new MO to coreData, permanentID is set only in context A for that MO, in contexts B and C MO still have temporaryID, does it correct behaviour of coreData or it's bug?
I expect that when I save MO to coreData, it will automatically update ID as permanent for MO in all context for this MO if it exist in registeredObjects of certain context
i need to make app that make Database of received Serial data
after receiving data , i need to show data using chart.
Serial data traffic is not high, and is not happen frequently...
and can i use FMDB at SwiftUI ?
Does the Reminders app use Core Data with CloudKit behind the scenes? I would like to know what approach is used to allow for re-ordering items and how conflicts are handled when move operations are done from multiple offline devices.
I've successfully followed the sample code from Apple: Synchronizing a local store to the cloud to deduplicate entities that are created in the user's private store.
However my app also has a public store that needs deduplication and if I enable the NSPersistentStoreRemoteChangeNotificationPostOptionKey for both the private and public store then no deduplication will occur in my private store.
This is reproducible every time by not setting NSPersistentStoreRemoteChangeNotificationPostOptionKey for the public store.
Has anyone else experienced this and has anyone got a solution to get it to work?
Persistence setup code:
private static func makeStoreDescription(for database: Database) -> NSPersistentStoreDescription {
let url: URL
let scope: CKDatabase.Scope
let configuration: String
switch database {
case .private:
url = Self.privateStoreURL
scope = .private
configuration = "Private"
case .public:
url = Self.publicStoreURL
scope = .public
configuration = "Public"
}
let storeDescription = NSPersistentStoreDescription(url: url)
storeDescription.cloudKitContainerOptions = .init(containerIdentifier: Config.cloudKitContainerIdentifier)
storeDescription.cloudKitContainerOptions?.databaseScope = scope
switch database {
case .private:
storeDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
storeDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
case .public:
// Uncommented otherwise deduplication doesn't work
// storeDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
// storeDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
break
}
storeDescription.configuration = configuration
return storeDescription
}
private static func makeContainer(inMemory: Bool = false, useIcloud: Bool) -> NSPersistentCloudKitContainer {
let privateStoreDescription = makeStoreDescription(for: .private)
let publicStoreDescription = makeStoreDescription(for: .public)
let container = NSPersistentCloudKitContainer(name: "Name", managedObjectModel: managedObjectModel)
container.persistentStoreDescriptions = [privateStoreDescription, publicStoreDescription]
// Don't save information for future use if running in memory...
if inMemory {
container.persistentStoreDescriptions.forEach { $0.url = URL(fileURLWithPath: "/dev/null") }
}
print("useIcloud:", useIcloud)
if !useIcloud {
container.persistentStoreDescriptions.forEach { $0.cloudKitContainerOptions = nil }
}
container.loadPersistentStores { storeDescription, error in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
print("Loaded store configuration:", storeDescription.configuration ?? "")
}
#if DEBUG
// Use the container to initialize the development schema.
// Only necessary whenever changes have been made to the schema.
//try! container.initializeCloudKitSchema(options: [])
#endif
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
container.viewContext.transactionAuthor = Self.transactionAuthor
if !inMemory {
do {
try container.viewContext.setQueryGenerationFrom(.current)
} catch {
fatalError("Failed to pin viewContext to the current generation: \(error)")
}
}
return container
}
My app is NOT using CoreData.
But I'm seeing this fault error in Console.app from mac when I build my iOS app:
CoreData: One or more models in this application are using transformable properties with transformer names that are either unset, or set to NSKeyedUnarchiveFromDataTransformerName. Please switch to using "NSSecureUnarchiveFromData" or a subclass of NSSecureUnarchiveFromDataTransformer instead. At some point, Core Data will default to using "NSSecureUnarchiveFromData" when nil is specified, and transformable properties containing classes that do not support NSSecureCoding will become unreadable.
What could be the cause of it?
What's the potential security issue it will cause to the app?
Hello,
I am building a list in SwiftUI, using the @FetchRequest property wrapper to fetch core data entities, taking as input a fetch request which has the property fetchBatchSize set to 50.
import SwiftUI
import CoreData
extension Item {
static var listRequest: NSFetchRequest<Item> {
let request = Item.fetchRequest()
request.fetchBatchSize = 50
request.sortDescriptors = [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)]
return request
}
}
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(fetchRequest: Item.listRequest)
private var items: FetchedResults<Item>
var body: some View {
NavigationView {
List {
ForEach(items) { item in
Text(item.timestamp!, formatter: itemFormatter)
}
}
}
}
}
But when loading my list with 3000 items and having the argument -com.apple.CoreData.SQLDebug enabled, there are 241 calls made to load my items 50 by 50 at a time. There is no mention of fetchBatchSize in the documentation, but this feature of fetch request is really important to me when building App dealing with large datasets of objects.
Am I doing something wrong or is there any recommandation about large data sets performances with SwiftUI lists indicating the best practices?
Thanks for your help !
Hello everyone,
I'm a complete beginner when it comes to programming and have been learning Swift for the past 2-3 months. I'm in the process of writing my very first project, an Apple Watch app for Tesla owners.
So far, I've managed to complete the UI aspect of the app and have recently begun diving into the coding part. However, I find myself a bit lost when it comes to connecting my app to the unofficial Tesla API.
On top of that, I'm also wondering if integrating Core Data is necessary for this kind of project?
If anyone could help me by providing a clear roadmap, it would greatly accelerate my research and learning process. Any tips, tutorials, or resources you could point me toward would be immensely helpful.
Thanks in advance for your assistance!
Best Regards
Sasan
I am having trouble using UndoManager with a private Manged Object Context in CoreData. Here is my setup: I have my main context running on the main queue. I created a private context via let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) and connect it as a child context to my main context via privateContext.parent = mainContext. I also assigned an UndoManager to privateContext. This UndoManger has been set to use manual grouping via undoManager.groupsByEvent = false. So far so good.
Now to the part that gives me trouble: I want to change something on the private context and record this action for potential undoing. In order to do this a use a nested grouping structure (that is how it makes sense in my code). This is how i currently do this:
privateContext.performAndWait {
undoManger.beginUndoGrouping
}
// do something in code unrelated to changes on the privateContext
privateContext.performAndWait {
doChangesOnPrivateContext()
}
privateContext.performAndWait {
undoManger.beginUndoGrouping
}
privateContext.performAndWait {
doChangesOnPrivateContext()
}
privateContext.performAndWait {
undoManger.endUndoGrouping
}
// do something in code unrelated to changes on the privateContext
privateContext.performAndWait {
undoManger.endUndoGrouping
}
This leads to the error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '_setGroupIdentifier:: NSUndoManager is in invalid state, must begin a group before registering undo
which I had encountered before when beginUndoGrouping and endUndoGrouping were called from different threads. Further examination yields that this is also the case here as performAndWait runs the code on the private queue assigned to privateContext, but with the structure shown above beginUndoGrouping and endUndoGrouping are indeed called on different threads.
So here are my questions:
How do I do this correctly?
Do I misunderstand things and UndoMangager should not be used on a private context? If so, how would I setup things then?
I'm having a weird issue. I have a watch app which communicates with the phone using a WCSessionDelegate.
if the phone app is open everything works fine, but if the app is closed, when the watch sends a message, my app is woken from the background, after which onAppear() is called in my app which causes a swiftData query to run.
Calling any swiftdata function from a backgrounded app causes it to immediately crash with the following stack trace. Any ideas what im doing wrong? or a better way to trigger my code instead of onAppear, so it won't be called when my watch wakes my app from the background?
.onAppear {
reloadData()
}
private func reloadData() {
let fetch = FetchDescriptor<SavedServer>(
predicate: nil,
sortBy: [.init(\.displayOrder)]
)
guard let results = try? modelContext.fetch(fetch) else {
self.rows = []
return
}
self.rows = results
}
-------------------------------------
Translated Report (Full Report Below)
-------------------------------------
Incident Identifier: 057999AF-7840-410E-B3EE-29082C5AED00
CrashReporter Key: 28AF2AA0-4626-9964-9664-36077DAF4E1A
Hardware Model: MacBookPro18,2
Process: MC Status [68915]
Path: /Users/USER/Library/Developer/CoreSimulator/Devices/C61698BA-C4CA-4DD9-B824-DBF57AC65090/data/Containers/Bundle/Application/A685371C-9174-4CF7-9E99-D573310CC3E5/MC Status.app/MC Status
Identifier: com.shemeshapps.MinecraftServerStatus
Version: 2.0 (1)
Code Type: ARM-64 (Native)
Role: Non UI
Parent Process: launchd_sim [55432]
Coalition: com.apple.CoreSimulator.SimDevice.C61698BA-C4CA-4DD9-B824-DBF57AC65090 [164301]
Responsible Process: SimulatorTrampoline [53834]
OS Version: macOS 13.4.1 (22F82)
Release Type: User
Report Version: 104
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Triggered by Thread: 0
Last Exception Backtrace:
0 CoreFoundation 0x18046589c __exceptionPreprocess + 160
1 libobjc.A.dylib 0x18005c09c objc_exception_throw + 56
2 CoreData 0x184989b94 -[NSFetchRequest(_NSInternalMethods) _incrementInUseCounter] + 0
3 CoreData 0x1849aa99c -[NSManagedObjectContext executeRequest:error:] + 164
4 CoreData 0x1848fe250 NSManagedObjectContext.fetch<A>(_:) + 80
5 SwiftData 0x1a89b7ad8 ModelContext.fetch<A>(_:) + 124
6 SwiftData 0x1a89c48c0 dispatch thunk of ModelContext.fetch<A>(_:) + 20
7 MC Status 0x102530ef4 MainAppContentView.reloadData(forceRefresh:) + 752 (MainAppContentView.swift:112)
8 MC Status 0x102533540 closure #2 in MainAppContentView.body.getter + 44 (MainAppContentView.swift:78)
9 SwiftUI 0x108a0b7a0 0x107b8c000 + 15202208
10 SwiftUI 0x108a0b7bc 0x107b8c000 + 15202236
11 SwiftUI 0x108a0b7a0 0x107b8c000 + 15202208
12 SwiftUI 0x108fdce70 0x107b8c000 + 21302896
13 SwiftUI 0x108fd6ec0 0x107b8c000 + 21278400
14 SwiftUI 0x1081edb24 0x107b8c000 + 6691620
15 SwiftUI 0x10928d650 0x107b8c000 + 24122960
16 libdispatch.dylib 0x1801424f4 _dispatch_call_block_and_release + 24
17 libdispatch.dylib 0x180143d3c _dispatch_client_callout + 16
18 libdispatch.dylib 0x180152b24 _dispatch_main_queue_drain + 1272
19 libdispatch.dylib 0x18015261c _dispatch_main_queue_callback_4CF + 40
20 CoreFoundation 0x1803c61b4 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
21 CoreFoundation 0x1803c08cc __CFRunLoopRun + 1936
22 CoreFoundation 0x1803bfd28 CFRunLoopRunSpecific + 572
23 GraphicsServices 0x189864bc0 GSEventRunModal + 160
24 UIKitCore 0x103b30208 -[UIApplication _run] + 868
25 UIKitCore 0x103b33e80 UIApplicationMain + 124
26 SwiftUI 0x108a10524 0x107b8c000 + 15222052
27 SwiftUI 0x108a103c4 0x107b8c000 + 15221700
28 SwiftUI 0x108722088 0x107b8c000 + 12148872
29 MC Status 0x102506d30 static MCStatusApp.$main() + 40
30 MC Status 0x102506de0 main + 12 (MCStatusApp.swift:12)
31 dyld_sim 0x1028fd558 start_sim + 20
32 dyld 0x1026b1f28 start + 2236
33 ??? 0x3c15800000000000 ???
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0 libsystem_kernel.dylib 0x102f1cfa8 __pthread_kill + 8
1 libsystem_pthread.dylib 0x10285712c pthread_kill + 256
2 libsystem_c.dylib 0x1801375ec abort + 104
3 libc++abi.dylib 0x180263c78 abort_message + 128
4 libc++abi.dylib 0x180255198 demangling_terminate_handler() + 300
5 libobjc.A.dylib 0x180037bf0 _objc_terminate() + 124
6 libc++abi.dylib 0x180263150 std::__terminate(void (*)()) + 12
7 libc++abi.dylib 0x180263100 std::terminate() + 52
8 libdispatch.dylib 0x180143d50 _dispatch_client_callout + 36
9 libdispatch.dylib 0x180152b24 _dispatch_main_queue_drain + 1272
10 libdispatch.dylib 0x18015261c _dispatch_main_queue_callback_4CF + 40
11 CoreFoundation 0x1803c61b4 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
12 CoreFoundation 0x1803c08cc __CFRunLoopRun + 1936
13 CoreFoundation 0x1803bfd28 CFRunLoopRunSpecific + 572
14 GraphicsServices 0x189864bc0 GSEventRunModal + 160
15 UIKitCore 0x103b30208 -[UIApplication _run] + 868
16 UIKitCore 0x103b33e80 UIApplicationMain + 124
17 SwiftUI 0x108a10524 0x107b8c000 + 15222052
18 SwiftUI 0x108a103c4 0x107b8c000 + 15221700
19 SwiftUI 0x108722088 0x107b8c000 + 12148872
20 MC Status 0x102506d30 static MCStatusApp.$main() + 40
21 MC Status 0x102506de0 main + 12 (MCStatusApp.swift:12)
22 dyld_sim 0x1028fd558 start_sim + 20
23 dyld 0x1026b1f28 start + 2236
I have an app Im moving over to cloudkit and it works fine on a new instance, but updating to this instance causes a perpetual crash and requires reinstall. I know this is because the persistence object changed. I was just using a normal NSPersistentController now a CK one, and there are two persistent stores, the public and private stores. Is there a way to either migrate the data properly, or atleast wipe the data model before it crashes and have it start anew? (I dont have many users and I know them personally so this would be acceptable)
I'm facing an issue in my iOS app's architecture involving CoreData, the HistoryCallDataService class, and the HistoryViewModel. I'm hoping someone can help shed light on the problem I'm encountering.
Problem Description:
I'm working with CoreData and have an array that I'm managing through the HistoryCallDataService class.
class HistoryCallDataService {
private let container: NSPersistentContainer
private let containerName = "CallHistoryData"
private let entityName = "HistoryData"
@Published var savedEntities: [HistoryData] = []
I'm observing changes in the savedEntities property of the HistoryCallDataService class using the historyDataService.$savedEntities publisher. When the app starts, the array is updated correctly. However, if I add new content, the savedEntities array updates, but the historyArray in the HistoryViewModel does not reflect these changes.
import Foundation
import Combine
class HistoryViewModel: ObservableObject {
@Published var searchText:String = ""
@Published var historyArray: [HistoryData] = []
private let historyDataService = HistoryCallDataService()
private var cancellables = Set<AnyCancellable>()
var selectedContact: HistoryData? = nil
@Published var filteredContacts: [HistoryData] = []
init(){
addSubscribers()
}
func addSubscribers(){
historyDataService.$savedEntities
.debounce(for: 1.0, scheduler: RunLoop.main)
.sink { [weak self] (returnData) in
guard let self = self else { return }
self.historyArray = returnData
self.updateFilteredContacts()
}
.store(in: &cancellables)
}
func updateFilteredContacts() {
if searchText.isEmpty {
filteredContacts = historyArray
} else {
filteredContacts = historyArray.filter { contact in
contact.firstName?.localizedCaseInsensitiveContains(searchText) ?? false ||
contact.lastName?.localizedCaseInsensitiveContains(searchText) ?? false ||
contact.telephone?.localizedCaseInsensitiveContains(searchText) ?? false
}
}
}
The view:
private var contactList: some View{
List{
ForEach(vm.filteredContacts) { item in
HStack{
VStack(alignment: .leading){
Text("\(item.firstName ?? "N/A") \(item.lastName ?? "N/A" )")
.fontWeight(.semibold)
Text("\(item.telephone ?? "N/A")")
.fontWeight(.medium)
.padding(.top,1)
}
Spacer()
VStack(alignment: .trailing){
Text("\(item.time ?? "N/A")")
.fontWeight(.medium)
Text("\(item.callHidden ? "Hidden" : "Normally ")")
.foregroundColor(item.callHidden ? Color.theme.red : Color.theme.black)
.fontWeight(.bold)
.padding(.top,1)
}
}
.onTapGesture {
vm.selectedContact = item
showingCallAlert.toggle()
}
.listRowBackground(vm.selectedContact?.telephone == item.telephone && showingCallAlert ? Color.theme.gray : nil)
}
.onDelete(perform: { indexSet in
for index in indexSet {
let contactToDelete = vm.filteredContacts[index]
vm.delete(entity: contactToDelete)
}
})
}
.onChange(of:
vm.searchText) { _ in
vm.updateFilteredContacts()
}
.onChange(of: scenePhase) { newPhase in
if newPhase == .active {
print("Active")
vm.updateFilteredContacts()
}
}
.lineLimit(1)
.listStyle(.plain)
}
If anyone has encountered a similar situation or has insights into what might be causing this behavior, I would greatly appreciate your guidance. Thank you in advance for your help!
I have narrowed my problem down to the many to many relationship between user and group record types. When a user transfers ownership of a group the new admin can change things like privacy (a field) but still only the original owner can leave or remove others. The new admin's use of remove user does nothing and no users can leave besides the creator. All security perms are enabled, and no permission not granted errors arise. I simply end up with two unsynced devices where one user observes themselves as having left, and the other that never will observe it. I can get around this a long way but don't really see why I should have to.
How can I keep the fetchLimit constant even when new data is inserted?
To replicate this, you can create a new Project in Xcode and check "Use Core Data". I use this code to apply fetchLimit:
struct MyView: View {
@FetchRequest private var items: FetchedResults<Item>
init() {
let request: NSFetchRequest<Item> = Item.fetchRequest()
request.fetchLimit = 3
_items = FetchRequest(fetchRequest: request)
}
This code works. For example I have 10 Items and when I open the app - only 3 are displayed! But when I add a new Item on the fly - @FetchRequest just adds it to the View and now it displays 4 Items!?
How can I make @FetchRequest keep updating the View reactively, but respect the fetchLimit to always show the latest 3 Items only?
coredata pushed schema to cloudkit only for those entities for which I created records. But the record data did not get pushed. I set recordName as Queryable and modifiedTimestamp as both Queryable and sortable. Query does not show the records. I look at Xcode console gives this output for one of the entities that got pushed to cloudkit :
CoreData: debug: CoreData+CloudKit: -[PFCloudKitSerializer newCKRecordsFromObject:fullyMaterializeRecords:includeRelationships:error:](575): Serializer has finished creating record: <CKRecord: 0x13f40f920; recordType=CD_Contact, recordID=26809600-B329-4C17-B3E1-6EA5FC177F7C:(com.apple.coredata.cloudkit.zone:__defaultOwner__), values={
"CD_contact" = "26809600-B329-4C17-B3E1-6EA5FC177F7C";
"CD_contactEmail_ckAsset",
"CD_contact",
"CD_contactEmail",
"<CKRecord: 0x13f40f920; recordType=CD_Contact, recordID=26809600-B329-4C17-B3E1-6EA5FC177F7C:(com.apple.coredata.cloudkit.zone:__defaultOwner__), recordChangeTag=5, values={\n \"CD_email\" = Email;\n \"CD_entityName\" = Contact;\n \"CD_firstName\" = V;\n \"CD_imageName\" = \"{ length=20834, sha256=d582bd2ccc7d93138b3a5ad4799443152860268e34f48ace54a0708f3e2f3aba }\";\n \"CD_lastName\" = R;\n \"CD_phone\" = 2;\n \"CD_screenName\" = Vr;\n \"CD_userRating\" = \"*****\";\n \"CD_userType\" = Household;\n}>",
Also schema for some other entities that do not have any core data records did not get pushed to CloudKit. I thought the entire coredata schema should get pushed along with the records. Looks like it is pushing those entities that have some records but without pushing data. I reset the cloudkit environment and tried again, but issue is not resolved.
Also the AppDelegate never gets called. I thought the line below should have called AppDelegate @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate: AppDelegate
Cross referenced persistenceController in AppDelegate. That did not help either
Code listed below. Please let me know how to fix the above two issues?
main
struct GreenApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate: AppDelegate
static var fcmToken: String?
let gcmMessageIDKey = "gcm.Message_ID"
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
}
struct PersistenceController {
static let shared = PersistenceController()
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
// for _ in 0..<10 {
// let newItem = Item(context: viewContext)
// newItem.timestamp = Date()
// }
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
return result
}()
let container: NSPersistentCloudKitContainer
init(inMemory: Bool = false) {
container = NSPersistentCloudKitContainer(name: "Green")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy // external changes trumping in-memory changes.
}
}
Appdelegate code:
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate, ObservableObject {
static var fcmToken: String?
let gcmMessageIDKey = "gcm.Message_ID"
let persistenceController = PersistenceController.shared
func applicationDidFinishLaunching(_ application: UIApplication) {
do {
// Use the container to initialize the development schema.
try persistenceController.container.initializeCloudKitSchema(options: [])
} catch {
// Handle any errors.
fatalError("###\(#function): failed to load persistent stores: \(error)")
}
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { granted, error in
})
} else {
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types:[.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
}
Hi all, My interface displays a text field bound to an NSNumber that I use internally as unsigned int. That NSNumber is actually saved with Core Data as Integer 16. However, the interface displays the number signed, meaning anything above 32.768 is actually shown to be negative.
I couldn't find a way to force my NSNumberFormatter to display unsigned numbers. Setting the minimum value to 0 also doesn't work, since internally it's gonna be positive anyway.
Could you help me display my 16-bit integer as an unsigned int between 0 and 65.535?
I am building a macOS app using Objective-C, macOS SDK 10.14 and Xcode 14.3.1.
I have a list of swiftdata objects I want to fetch and show in a swift UI list. My problem is the swiftdata object in my DB is not the object I directly want to use in my view. I want to map it to a different viewModel and use that which makes my life wayyy easier.
problem is every single example I see online of swift data, just uses the magic @Query operator to get their data, and then directly show it on the UI.
What's the best way for me to load the data on initialization but map it to a different type? I've tried this, but it just crashes.
init() {
do {
modelContainer = try ModelContainer(for: MY_DATA_CLASS.self)
} catch {
fatalError("Could not initialize ModelContainer")
}
let serverList = FetchDescriptor<MY_DATA_CLASS>(
sortBy: [SortDescriptor(\.displayOrder)]
)
do {
viewModels = try modelContext.fetch(serverList).map {
ViewModel(server: $0)
}
} catch {
print(" WHAT THE HECKKK: " + error.localizedDescription)
}
}
NSFetchRequest could not locate an NSEntityDescription for entity name ....
any suggestions greatly appreciated. Using @query works fine so I know the rest of the DB is setup correctly.
hi,
this is a very simple concept that I can't seem to solve using relationships with core data between two tables. for instance, I have a client table with a name field that I want to link to a client details table with a clientName field and when I update/edit the client name, this still stays links to the client details record. make sense?
I tried relationships but it does not link up when I edit the client name. I feel like I'm missing something very obvious here and have tried multiple scenarios but I'm not finding a solution nor am I finding any documentation on how this should work.
any help/ideas is appreciated.
Thank you,
Pete
I've a large data feed to load in database. this data populate many entities that are related each others. I've follow this official tutorial - https://developer.apple.com/documentation/coredata/loading_and_displaying_a_large_data_feed to use nsbatchInsertRequest.
But this tutorial has one big bug: populate data only in one entity. How many apps use a database with only one entity?
therefore the problem that I have not only me, but several people, is time. With nsbatchinsertrequst I was able to insert more than 30000 records in just 5 seconds with a use of just 25MB of RAM. But without setting up relationships. if after the execution of the various insertrequests I set the relations, everything takes me about 50 seconds with an increase in memory to 60-70 MB.
Is it possible that there is no way to quickly set up relationships? Not only that, this is a forum where Apple engineers, who therefore know the subject better, should give help. but who knows why, for such questions they disappear. Maybe it's my posts that are so boring that Apple ignores them? Or are they so difficult that even apple engineers can't solve them? Who knows if I'll ever find the answer! But is it possible that they don't have a solution? These Apple engineers if they had the same problem as me, how would they solve it? they simply say: "it can't be done! Arrange!"?
anyway, I hope that some Apple engineer or someone experienced will be able to find the solution at least to this problem. Or it will be another zombie post in the billions of zombie posts of people like me who pay $ 100 but get no support.
Thank you