Modifying Core Knowledge merchandise generates new UUID, inflicting duplication
I am making an iOS utility utilizing UIKit, SwiftUI, and Core Knowledge.
It is working positive when including or deleting objects, however I am encountering a problem when attempting to edit (replace) an merchandise’s particulars.
The issue is that when I attempt to edit an merchandise, a brand new UUID is generated, which causes the merchandise to be duplicated as an alternative of updating the present one.
Right here is the related code:
File Title: DetailView.swift
import SwiftUI
struct QSOLogDetailView: View {
@State var log: QSOLog
@State non-public var isEditing = false // 編集モードを管理
var onSave: (QSOLog) -> Void
var physique: some View {
Kind {
/* Omission */
TextField("Pattern", textual content: $log.dataname)
/* Omission */
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
if isEditing {
Button("Save") {
onSave(log)
isEditing = false
}
} else {
Button("Edit") {
isEditing = true
}
}
}
}
}
}
Right here is how the QSOLog struct is outlined:
file identify: TypeLog.swift
import Basis
import CoreData
/* Omission */
struct QSOLog: Identifiable {
var id = UUID() // 一意のIDを追加
var dataname: String
var time: Date
/* Omission */
// Switch to CoreData
func toEntity(context: NSManagedObjectContext) -> QSOLogEntity {
let entity = QSOLogEntity(context: context)
entity.dataname = dataname
entity.time = time
/* Omission */
return entity
}
}
// switch QSOLogEntity to QSOLog
extension QSOLogEntity {
func toQSOLog() -> QSOLog {
return QSOLog(
id: self.id ?? UUID(), // Generate new UUID if merchandise would not have it.
dataname: self.dataname ?? "",
time: self.time ?? Date(),
/* Omission */
)
}
}
When including a brand new merchandise, I’m utilizing the next code:
File Title: NewEntry.swift
var onSave: (QSOLogEntity) -> Void
/* Omission */
Button("Save") {
saveLog() // Name knowledge to retailer in Core Knowledge
}
/* Omission */
func saveLog() {
let fetchRequest: NSFetchRequest = QSOLogEntity.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "dataname == %@ AND time == %@", log.dataname, log.time as CVarArg)
do {
let existingLogs = strive context.fetch(fetchRequest)
if existingLogs.isEmpty {
let newLog = QSOLogEntity(context: context)
newLog.dataname = log.dataname
newLog.time = log.time
/* Omission */
strive context.save()
onSave(newLog)
presentationMode.wrappedValue.dismiss()
} else {
}
} catch {
print("It is getting Error")
}
}
And QSOLogEntity is outlined in different file.
File Title: TypeLog.swift
extension QSOLogEntity {
func toQSOLog() -> QSOLog {
return QSOLog(
id: self.id ?? UUID(), // Get new UUID when would not have it.
dataname: self.dataname ?? "",
time: self.time ?? Date(),
/* Omission */
)
}
}
I’ve been attempting to resolve this for not less than 10 hours, however I can’t appear to discover a answer. That is my first time creating an app. If anybody may assist me clear up this downside, I might tremendously recognize it.