如何使用for循环在核心数据中创建实体?

时间:2017-03-23 14:48:30

标签: swift core-data swift3

希望你们做得好。我的数据库中有2个实体:一个是具有总楼层数属性的房子,第二个是具有属性楼层数的楼层(房屋中的楼层数)。有1到多个rel。楼层和房间之间。如果我插入3个楼层,我需要3个单独的楼层实例,这样我就可以为每个楼层分配房间 我正在努力的是如何使用for循环创建正确数量的Floors实体,这样我就可以为每个实体分配房间数量(Room是一个具有不同属性的不同实体)。请看下面我的尝试,如果你能尝试帮助我。

class SetNumberOfFloorsVC: UIViewController {

//MARK: - Properties

@IBOutlet private weak var numberOfFloorsTxt: UITextField!

private var managedObjectContext: NSManagedObjectContext!

private var floorNumberValue: Int16 {
    get {
        return Int16 (numberOfFloorsTxt.text!)!
    }
}

//MARK: - Actions

override func viewDidLoad() {
    super.viewDidLoad()
    managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}



@IBAction private func setTheNumberOfFloors(_ sender: UIButton) {
    if let correctType = floorNumberValue as? Int16 { // ignore the warning because I need to check if the value is for sure Int16.
        let house = House(context: managedObjectContext)
        house.numberOfFloors = correctType
        print("\(house.numberOfFloors)")

        let floor = Floors(context: managedObjectContext)
        for i in 0...house.numberOfFloors {
            floor.floorNumber = Int16(i)
            print("\(floor.floorNumber)")
        }
    } else {
        let screenAlert = UIAlertController(title: "Warning!", message: "Incorrect value. Only single or double digit numbers please!", preferredStyle: .alert)
        screenAlert.addAction(UIAlertAction(title: "Got it!", style: .default, handler: nil))
        self.present(screenAlert, animated: true, completion: nil)
    }


}


// MARK: - Navigation

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let identifier = segue.identifier {
        switch identifier {
        case "assign number of rooms": if let vc = segue.destination as? SetNumberOfRoomsPerFloor {
            vc.floorValue = floorNumberValue
            }
        default: break
        }
    }
}

0 个答案:

没有答案