Question is.
How can I insert the following code in SwiftUI into the database to add to an array and delete at the specified point in SwiftData?
This was a mistake in
Post
Replies
Boosts
Views
Activity
It was an elementary question.
Self resolved. My apologies.
Thanks for answering.
Indeed, it is working as it should.
However, it does not work when it is closer to the actual method used as shown below, is this the wrong way to do it?
@Observable
class ViewModel {
static let shared = ViewModel()
var hours: Int = 0
var minutes: Int = 0
var seconds: Int = 0
func testTimer() {
print("init")
Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { _ in
self.seconds += 1
if self.seconds == 60 {
self.minutes += 1
if self.minutes == 60 {
self.hours += 1
}
}
}
}
}
struct ContentView: View {
let viewmodel = ViewModel.shared
@State var model = ViewModel()
var body: some View {
VStack {
Text("\(model.hours):\(model.minutes):\(model.seconds):")
Button {
viewmodel.testTimer()
} label: {
Text("Timer Start")
}
}
}
}
So the following CoreData can also be written as SwiftData?
func fetchPersistentHistory() {
let context = persistentContainer.newBackgroundContext()
context.perform {
let lastToken = self.loadLastToken()
let request = NSPersistentHistoryChangeRequest.fetchHistory(after: lastToken)
if let result = try? context.execute(request) as? NSPersistentHistoryResult,.
let transactions = result.result as? [NSPersistentHistoryTransaction] {
for transaction in transactions {
self.process(transaction: transaction)
}
self.saveLastToken(from: transactions.last)
}
}
}
private func process(transaction: NSPersistentHistoryTransaction) {
let context = persistentContainer.viewContext
context.perform {
transaction.changes?.forEach { change in
if change.changedObjectID.entity.name == “MyEntity” {
self.applyChanges(from: change)
}
}
}
}
private func applyChanges(from change: NSPersistentHistoryChange) {
switch change.changeType {
case .insert:.
self.restoreEntity(for: change.changedObjectID)
case .update: self.updateEntity(for: changedObjectID)
self.updateEntity(for: change.changedObjectID)
case .delete: self.deleteEntity(for: change.changedObjectID)
self.deleteEntity(for: change.changedObjectID)
default: break
break
}
// record changes in MyEntityHistory
if let entityID = change.changedObjectID.uriRepresentation().absoluteString.components(separatedBy: “/”).last {
addHistoryRecord(entityID: entityID, changeType:. “\(change.changeType)")
}
// Refresh the entity list after applying changes
fetchEntities()
}
func addHistoryRecord(entityID: String, changeType: String) {
let context = persistentContainer.viewContext
let historyRecord = MyEntityHistory(context: context)
historyRecord.id = UUID()
historyRecord.entityID = entityID
historyRecord.timestamp = Date()
historyRecord.changeType = changeType
do {
try context.save()
} catch {
print("Failed to save history record:. \(error)")
}
}