以一对多关系保存数据

时间:2017-04-25 07:02:28

标签: ios swift core-data swift3

我的核心数据模型看起来像这样。

enter image description here

以下功能将出勤数据保存为员工的一部分(应在凭证表中提供)。

func addOrUpdateAttendanceReport(data: [AttendanceSummaryInfoDTO]){

    let doesEmpExist = validateEmpCredentials(ofThe: EmpCredentialsDTO(empMailId: currentActiveEmpId, empPassword: ""))

    if doesEmpExist{
        let emp = getCurrentEmpRecord(ofTheEmployee: currentActiveEmpId)

        var attendanceSummarySet = [Attendance]()
        for info in data
        {
            let attendanceInfo = Attendance(context: dbContext)
            attendanceInfo.status = info.leaveType
            attendanceInfo.reptDate = info.reptDate

            attendanceSummarySet.append(attendanceInfo)
        }
        emp.attendanceReport = NSSet(array: attendanceSummarySet)

        do{
            try dbContext.save()

        } catch {
            print("Error: \(error)")  // something bad happened, handle this situation appropriately

        }

    }
    else{
        print("Unable to save attendance summary info because, there is no employee exist with current id in local database ")
    }
}

数据保存成功,但是当我使用simMagnifier工具查看记录时,空记录与实际记录一起保存在凭据表中。

当我再次运行它时,另一个空记录将保存在凭证表中,同时保存在出勤表中,父级为空。

我无法找出导致此问题的原因。我的工作环境是Xcode 8.3.1,iOS 10.3.1和swift 3。

附加代码:

func getCurrentEmpRecord(ofTheEmployee id: String) -> Credentials {

let emp = Credentials(context: dbContext)
let fetchRequest: NSFetchRequest<Credentials> = Credentials.fetchRequest()

fetchRequest.predicate = NSPredicate.init(format: "empId == %@", id)

do {
    let searchResults = try dbContext.fetch(fetchRequest)
    if searchResults.count > 0 {
        for record in searchResults {
            return record
        }
        return emp
    } else {
        return emp
    }
} catch {
    print("Error: \(error)")
    return emp
}
}

1 个答案:

答案 0 :(得分:2)

每次调用Credentials时都会创建一个空的getCurrentEmpRecord(),因此如果存在给定Credentials的{​​{1}},则会在CoreData中获得一个额外的空条目。

仅在不存在时创建它:

id

更新

我如何理解方法的名称(“getCurrentEmpRecord”),您根本不想创建一个空的func getCurrentEmpRecord(ofTheEmployee id: String) -> Credentials { //let emp = Credentials(context: dbContext) // do not create emp here ... let fetchRequest: NSFetchRequest<Credentials> = Credentials.fetchRequest() fetchRequest.predicate = NSPredicate.init(format: "empId == %@", id) do { let searchResults = try dbContext.fetch(fetchRequest) if searchResults.count > 0 { return searchResults.first! } } catch { print("Error: \(error)") } let emp = Credentials(context: dbContext) // ... but only if you need to create it return emp } ,即使没有给定Credential的{​​{1}}也是如此存在。

emp