CoreData - 一对多关系

时间:2015-08-14 15:14:39

标签: swift core-data one-to-many nsfetchedresultscontroller relationships

我将发布以下代码然后解释我的斗争

此功能可以节省一天(如星期日,星期一,星期二等):

func appendDaysToArray() {
        let dayLabel = dayName.text
        daysArray.append(dayLabel)

        let dayEntity = NSEntityDescription.entityForName("TrainingDay", inManagedObjectContext: moc!)
        let trainingday = TrainingDay(entity: dayEntity!, insertIntoManagedObjectContext: moc)
        trainingday.day = dayName.text

        var error: NSError?
        moc?.save(&error)

        if let err = error {
            var status = err.localizedFailureReason
            println("\(status)")
        } else {
            println("Day #\(dayName.text) saved successfully!")
        }
    }

并且这个将详细信息保存为名称,多组和重复次数(如健身房练习):

func appendTrainingDetails () {

        let nameLabel = exerciseName.text
        namesArray.append(nameLabel)
        let numberOfSets = setsNumber.text?.toInt()
        setsArray.append(numberOfSets!)
        let numberOfReps = repsNumber.text?.toInt()
        repsArray.append(numberOfReps!)

        let detailsEntity = NSEntityDescription.entityForName("TrainingDetails", inManagedObjectContext: moc!)
        let trainingdetails = TrainingDetails(entity: detailsEntity!, insertIntoManagedObjectContext: moc)
        trainingdetails.exerciseName = exerciseName.text
        trainingdetails.setsNumber = setsNumber.text!
        trainingdetails.repsNumber = repsNumber.text!


        var error: NSError?
        moc?.save(&error)

        if let err = error {
            var status = err.localizedFailureReason
            println("\(status)")
        } else {
            println("Exercise: #\(exerciseName.text) saved successfully!")
            println("Number of sets: #\(setsNumber.text) saved successfully!")
            println("Number of reps: #\(repsNumber.text) saved successfully!")
        }
    }

我的应用程序运行正常,但我真正需要的是:对于每一天,我将有多个exerciseNames,setsNumber和repsNumber。我设置了一对多关系,但我不知道如何将daysDetails属于daysArray中的每一天。

以下是我的2个型号:

import Foundation
import CoreData

class TrainingDay: NSManagedObject {

    @NSManaged var day: String
    @NSManaged var relationship1: NSSet

}

import Foundation
import CoreData

class TrainingDetails: NSManagedObject {

    @NSManaged var exerciseName: String
    @NSManaged var repsNumber: String
    @NSManaged var setsNumber: String
    @NSManaged var relationship2: TrainingDay

}

稍后,我每天都会有一个按钮,按下后,他们会使用该特定日期的练习列表更新tableView。这就是我需要设置这种一对多关系的原因。

我怎样才能做到这一点?

对于任何错误抱歉。在此先感谢!!

0 个答案:

没有答案