Core Data RelationShip Swift

1

I have the following example to understand the relationships between entities in Core Data , (brand model), I have car brands respectively and now I want to add models to these car brands for this I have registered in vieDidLoad some brands and When I choose a brand, I set a UIAlertViewController where it will allow me to capture a model for this brand but I do not know how to relate this model to that previously created object , assuming it was something dynamic. Next I add my code; the id of the objects I keep in an array of String and now I compare it with a Predicate but the result that returns to me comes out with quotes. In the predicate of the fix Id[indexPath.row]

with quotes in the predicate

* predicate: SELF == "0xd000000000040000<x-coredata://A94EA723-56E4-475B-8D1B-582FC4C58CCD/MARCA/p1>"

NSOBJECT without quotes

*  predicate: SELF == 0xd000000000040000<x-coredata://A94EA723-56E4-475B-8D1B-582FC4C58CCD/MARCA/p1>

//
//  ViewController.swift
//  Audi
//
//  Created by MACBOOK on 28/04/16.
//  Copyright © 2016 mossito. All rights reserved.
//

    import UIKit
    import CoreData


    let appDelegado:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let contexto:NSManagedObjectContext = appDelegado.managedObjectContext

    class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
        @IBOutlet weak var myTable: UITableView!

        var textFeild:UITextField!

        var arreglo:[String] = [String]()
        var arreglosId:[String] = [String]()
        //var tamano:Int = 0

        override func viewDidLoad() {
            super.viewDidLoad()


            let entityMarca =  NSEntityDescription.entityForName("MARCA", inManagedObjectContext: contexto)

            let newMarca = NSManagedObject(entity: entityMarca!, insertIntoManagedObjectContext: contexto)
            newMarca.setValue("NISSAN", forKey: "nombre")


            let newMarca1 = NSManagedObject(entity: entityMarca!, insertIntoManagedObjectContext: contexto)
            newMarca1.setValue("FIAT", forKey: "nombre")
            //print(newMarca1)

            let newMarca2 = NSManagedObject(entity: entityMarca!, insertIntoManagedObjectContext: contexto)
            newMarca2.setValue("BWM", forKey: "nombre")
            //print(newMarca2)

            let newMarca3 = NSManagedObject(entity: entityMarca!, insertIntoManagedObjectContext: contexto)
            newMarca3.setValue("FORD", forKey: "nombre")
            //print(newMarca3)

            let newMarca4 = NSManagedObject(entity: entityMarca!, insertIntoManagedObjectContext: contexto)
            newMarca4.setValue("CHEVROLET", forKey: "nombre")
            //print(newMarca4)

            let newMarca5 = NSManagedObject(entity: entityMarca!, insertIntoManagedObjectContext: contexto)
            newMarca5.setValue("FERRARI", forKey: "nombre")
            //print(newMarca5)
            do{
                //Inserto(guardo) en BD
                try contexto.save()
                //print(newMarca.description)
                print("Insertando marca")
            }catch {
                print("Aqui hubo un error:-----\(error)")
            }


            arreglo.removeAll()

            let consulta = NSFetchRequest(entityName: "MARCA")
            if let resultados = try?contexto.executeFetchRequest(consulta) {

                for x in resultados {
                    arreglo.append("\(x.valueForKey("nombre")!)")
                    arreglosId.append("\(x.objectID)")
                }
            }



        }
        override func viewDidAppear(animated: Bool) {
            super.viewDidAppear(animated)


        }

        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

            let celda = UITableViewCell(style:UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
            celda.textLabel?.text = arreglo[indexPath.row]
            return celda
        }

        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return arreglo.count
        }


        func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
            var identificador = arreglosId[indexPath.row]
            var valorTexto:String =  ""
    //        
      // let newMarca = NSEntityDescription.insertNewObjectForEntityForName("MARCA", //inManagedObjectContext: contexto)
       // newMarca.setValue("x", forKey: "nombre")
         //   _ = try? contexto.obtainPermanentIDsForObjects([newMarca]);

         let alerta = UIAlertController(title:"Agrega modelo", message: "Registra un nuevo modelo ha esta marca", preferredStyle:.Alert)
            alerta.addTextFieldWithConfigurationHandler(configuredTextField)
            let action =  UIAlertAction(title: "OK", style: .Default, handler: {
                (alerta)->Void in
                 valorTexto = self.textFeild.text!
                print(valorTexto)
                let consulta = NSFetchRequest(entityName: "MARCA")
                /**========= PROBLEMA*/
                consulta.predicate = NSPredicate(format: "SELF = %@", NSManagedObject(self.arreglosId[indexPath.row]))
                 print("consulta \(consulta)")
                if let results =  try? contexto.executeFetchRequest(consulta) where results.count > 0 {
                    for x in results {
                    print("valor de x  \n\(x)")
                    }
                }else{
                   print("No hay registros")
                }
            })
           alerta.addAction(action)
           presentViewController(alerta, animated: true, completion: nil)

        }

        /**Metodo para configurar el textField  el textField*/
        func configuredTextField(text:UITextField! ){
            text.placeholder = "Descripción"
            textFeild = text
        }
    }

Image 1

Image 2

    
asked by Isa M 30.04.2016 в 22:14
source

1 answer

1

The relationship in CoreData must be taken as if they were objects. In the end, what CoreData tries to do is some SQLite3 records that are treated as if they were objects, and not worrying about relationships, deletions, etc. The first thing would be to see how you have the data model created. You have a brand that can have 1 or several models (1-N ratio), and with respect to deletion, if you eliminate a brand you should eliminate all models but if you delete a model you should still have the mark (Delete rule Cascade or Nullify)

You create the entities and configure that the model relationship is "type To Many" and "delete rule Cascade"

And now you believe the inverse, when you want to manage a model

Well, to relate between model and brand is very simple. You have to have created a brand model, that's what you're doing with

let newMarca = NSManagedObject(entity: entityMarca!,        insertIntoManagedObjectContext: contexto)
        newMarca.setValue("NISSAN", forKey: "nombre")

Well now, newMarca also has newMarca.modelo. What you have to do is create the model and relate it as if it were an object, CoreData for the rest

let newModelo = NSManagedObject(entity: entityModelos!, insertIntoManagedObjectContext: contexto)
        newModeloCoche.setValue("ModeloX", forKey: "modeloCoche")

And the magic comes when you do:     newMarca.modelo = newModel

To the question you ask about why the mark does not appear, it is because it is a fault. It is a way of working with core data. It means that there is something, but since you have not asked for it, Core Data has not lost time or resources in going to look for it. If you need it then it will look for it. If you look for brands in the entity, you can see that there is a fault in the models, they are there, but you have only searched for brands. As soon as you ask to take out the models, then Core Data accesses the disk and gives you the models. If you have a lot of data, it may also happen that at a certain time the oldest records pass them to fault, thus free memory. So for the faults do not get scared

    
answered by 01.05.2016 в 08:50