在Swift中的CoreData模型(实体之间的关系)中创建链接值

时间:2016-03-23 22:06:56

标签: swift core-data uipickerview relationships

我有一个问题:

我想在核心数据模型中添加值与实体之间的关系,并在视图中使用pickersView显示这些值。

我创建了一个示例,试图了解如何实现实体之间的关系,但现在我处于待机状态......我不知道如何在我的模型中使用mutableSetValueForKey,valueforkey,setvalue(_:forkey)。在我的例子中,设备或卡片链接到上面的项目。

我的coreData模型:3个实体:用户,设备和卡 用户 - 设备(nn):n个设备到n个用户 设备 - 卡(1n):1个设备可以有多个卡,但一个卡仅用于一个专用设备

见模型图片:

CoreData Model

要填充,我有一个包含多个字段的视图,Pickers,buttons:

Usertexfield +添加按钮添加新用户

  • 用户的选择器(显示/sélect用户)+ devicetextfield +添加按钮以向用户添加新设备

  • 设备的选择器(显示/sélect设备)+ cardtextfield +添加按钮以将新卡添加到设备

  • Picker of cards(显示/sélect卡)

  • 删除设备按钮以删除设备

  • 删除卡片按钮以删除卡

我还希望能够在选择时修改设备或卡(非制作)

问题 : 如何创建/修改/删除与用户关联的设备(如何在fetchrequest中实现这两个实体之间的关系?

这是我的代码(根本没有完成...):请参阅addDeviceButton函数(如果可能的话还要添加addCardButton)

    //  createRelationshipsViewController.swift
    //  testcoredatarelationships
    //
    //  Created by jIOP on 23/03/2016.
    //  Copyright © 2016. All rights reserved.
    //

    import UIKit
    import CoreData

    class createRelationshipsViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

        // User
        @IBOutlet weak var pickerUser: UIPickerView!
        @IBOutlet weak var userNameTextField: UITextField!
        @IBOutlet weak var boutonAddUser: UIButton!


        // Device
        @IBOutlet weak var pickerDevice : UIPickerView!
        @IBOutlet weak var deviceNameTextField: UITextField!
        @IBOutlet weak var boutonAddDevice: UIButton!
        @IBOutlet weak var deleteActivite: UIButton!

        //Card
        @IBOutlet weak var pickerCard : UIPickerView!
        @IBOutlet weak var carteNameTextField: UITextField!
        @IBOutlet weak var boutonAddcard: UIButton!
        @IBOutlet weak var deleteCard: UIButton!

        //Actions

        var tabpickerUser=[]
        var tabpickerDevice=[]
        var tabpickerCard=[]


        override func viewDidLoad() {
            super.viewDidLoad()


                    // init PickerView User only -others can't be at this time

            let MOC = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
            let fetchRequest = NSFetchRequest(entityName: "User")
            var requestError: NSError?

            /* And exécute the fetch request on the context */
            usersInCD = (try! MOC.executeFetchRequest(fetchRequest)) as! [User]
            //   usersInCD is a list of Users  
            // tbd --> if nil picker is empty else init tabpickerUser with usersInCD.Name.

              }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }


        @IBAction func addUserBoutonAction(sender: AnyObject) {

            let MOCUser = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
            let newUser = NSEntityDescription.insertNewObjectForEntityForName("User",inManagedObjectContext: MOCUser) as! User

            newUser.userId = NSUUID().UUIDString
            newUser.userName = userNameTextField.text // new user textfield

            var savingError: NSError?
            do {
                try MOCUser.save()
                print("New User created")

            } catch let error1 as NSError {
                savingError = error1
                if let error = savingError
                {
                    print("Failed to populate the database User. Error = \(error)")

                }
        // Update UserPicker --> Tbd

        }

        @IBAction func addDeviceBoutonAction(sender: AnyObject) {

            let MOCDevice = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

            // How to get userId from PickerView 
            // How to create a new device attached to this userId (predicate, mutableSetValueForKey, other ...)

            let newDevice = NSEntityDescription.insertNewObjectForEntityForName("Device",inManagedObjectContext: MOCDevice) as! Device

            newDevice.deviceId = NSUUID().UUIDString
            newDevice.deviceName = deviceNameTextField.text

            var savingError: NSError?
            do {
                try MOCDevice.save()
                print("New device created")

            } catch let error1 as NSError {
                savingError = error1
                if let error = savingError
                {
                    print("Failed to populate the database Device. Error = \(error)")

                }
        }


        @IBAction func addCardBoutonAction(sender: AnyObject) {

        // same PB but with n--1 relationships between Device and Cards 
        // A card is associated to 1 device only / one device car have several cards
        // usage of mutableSetValueForKey ?

        }


        @IBAction func deleteDeviceBoutonAction(sender: AnyObject) {
            // How to delete device (device) --> device will delete the card ?


        }


        @IBAction func deleteCardBoutonAction(sender: AnyObject) {
                    // How to delete card, link to a device
        }

/////////////////////////// Picker managment        

        func numberOfComponentsInPickerView(pickerView:UIPickerView) -> Int {
            return 1
                }

        func pickerView(pickerView: UIPickerView,numberOfRowsInComponent component:Int) -> Int {

            switch pickerView.tag {
            case 1:
                return tabpickerUser.count
            case 2:
                return tabpickerDevice.count
            case 3:
                return tabpickerCard.count
            default:
                print("Something else")
            }

        }

        func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {

            switch pickerView.tag {
                case 1:
                    return tabpickerUser[row] as! String
                case 2:
                    return tabpickerDevice[row]as! String
                case 3:
                    return tabpickerCard[row]as! String
                default:
                    print("Something else")
                }

        }



  // Here add pickerView functions to update pickers views when user, device, card is added or remove.
// not done ...           
        /*     Init pickerView Device and pickerView Card (how to do it ?)
               Init pickerView Device when user is selected in UserpickerView

                let MOC = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

                 // predicate to match UserId in Entity Device ?? how to do it using the relationships ????
                 //let predicate = NSPredicate(format: "userId == %@", tabpickerUser[row].userId!)   ???????
                 fetchRequest.predicate = predicate

                  var requestError: NSError?
                  /* And execute the fetch request on the context */
                  Devices = (try! MOC.executeFetchRequest(fetchRequest)) as! [Device]

        */


        /*       Init pickerViewCard when Device is selected in DevicepickerView

                let MOC = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
                let fetchRequest = NSFetchRequest(entityName: "Card")
                var requestError: NSError?

                // And execute the fetch request on the context
                Cards = (try! MOC.executeFetchRequest(fetchRequest)) as! [Card]
        */
        }

0 个答案:

没有答案