Swift Real - 如何将数据附加到在不同类中创建的Object

时间:2018-04-18 12:21:07

标签: ios swift realm

当我尝试将值添加到在不同类中创建的Object时,我遇到了问题。 那是我的数据库模型:

import Foundation
import RealmSwift

class User: Object {

    @objc dynamic var height : Int = 0
    @objc dynamic var age : Int = 0
    @objc dynamic var sex : String = ""
    @objc dynamic var physicalActivity : Float = 1.0
    @objc dynamic var goal : String = ""
    var meals = List<Meals>()
    var weightProgress = List<WeightProgress>()
    var calories = List<Calories>()

    func calculateBMI() -> Double {

        let BMI : Double = (self.weightProgress.last?.weight)! / (Double(self.height / 100) * Double(self.height / 100))
        return BMI

    }

    func calculateBMR() -> Double {

        var calories : Double = 0.0
        let currentWeight = self.weightProgress.last?.weight
        let height = self.height
        let age = self.age

        if self.sex == "Mężczyzna" {
            calories += 66
            calories += (13.7 * currentWeight!)
            calories += Double(5 * height)
            calories -= (6.76 * Double(age))
        }
        else {
            calories += 655
            calories += (9.6 * currentWeight!)
            calories += Double(1.8 * Double(height))
            calories -= (4.7 * Double(age))
        }

        return calories

    }

}

class Meals: Object {

    @objc dynamic var mealsCount : Int = 0
    @objc dynamic var meal1 : String?
    @objc dynamic var meal2 : String?
    @objc dynamic var meal3 : String?
    @objc dynamic var meal4 : String?
    @objc dynamic var meal5 : String?
    @objc dynamic var meal6 : String?
    @objc dynamic var meal7 : String?

}

class WeightProgress : Object {

    @objc dynamic var date : String?
    @objc dynamic var weight : Double = 0.0

}

class Calories : Object {

    @objc dynamic var date : String?
    @objc dynamic var eatenCalories : Int = 0

}

func getDateWithoutTime() -> String {

    let date = NSDate()

    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = .none
    dateFormatter.dateStyle = .short

    return dateFormatter.string(from: date as Date)

}

On One VC我创建一个User对象并设置一些数据(高度,年龄,性别,目标类型,用餐次数),在第二个VC上我想通过添加有关权重的信息来扩展User对象,并附加weightProgress列表另一个对象(WeightProgress)。当我尝试设置权重数据并附加weightProgress列表时,我应该如何引用现有的User对象?

由于 IMAT

2 个答案:

答案 0 :(得分:0)

初始化该特定类的对象并访问该类的元素。

答案 1 :(得分:0)

你有几个传递对象的选项,但我相信最好的选择是将对象保存在Realm中,然后在另一个控制器中获取它,进行所需的更改并再次保存。