why I can't access my 3rd level CoreData data in swift?

天涯浪子 提交于 2019-12-10 11:48:27

问题


I have this model:

And In one of my ViewController classes I created a method with 3 do while loops (a nested loop) where I insert all the "cursos", "temas" and "subtemas" to populate all my coreData model.

So, inside that method I put this loop to access a part of my coreData data to see if my nested loop work, I did it like this:

    var i = cursos.count
    var index = 0


    do{

        println(cursos[index].nombre)
        println(cursos[index].temas[0].nombre)
        println(cursos[index].temas[0].subTemas[0].nombre)

        index++
    }while(index < i)

"cursos" is my NSManaged object array containing all my "cursos", so in that last loop I think I access the "subTema" data of my first "curso" with the first "tema".

Well, everything went like I want, but When I tried to access the same data in another class (my original goal: have access to my data anywhere), my method to access the data don't recognised my "subTemas" stack of NSManagedObjects linked to my other two stacks of NSManagedObjects. Example:

Maybe I need to access my data in another way, through my relationships perhaps? if that so, how can I do it? I really need your help, thanks !

Update: My NSManagedObjects Subclasses generated by Xcode:

Curso.swift

 import Foundation
 import CoreData

 class Curso: NSManagedObject {

 @NSManaged var msjBienvenida: String
 @NSManaged var nombre: String
 @NSManaged var nombrePng: String
 @NSManaged var temas: NSOrderedSet

    }

Tema.swift

  import Foundation
  import CoreData

  class Tema: NSManagedObject {

  @NSManaged var nombre: String
  @NSManaged var curso: Curso
  @NSManaged var subTemas: NSOrderedSet

  }

SubTema.swift

 import Foundation
 import CoreData

 class SubTema: NSManagedObject {

 @NSManaged var nombre: String
 @NSManaged var tema: Tema

 }

Update 2 (relevant code for MartinR):

Inside the VC where I will make a web service call to fill my coreData data, here I don't have to cast my arrays, I can access my data like cursos[index].temas[0].subtemas[ 1 ].name , why ? :

  func webServiceCall2(index:Int){


   var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

   var exeWebServiceCall2 = defaults.objectForKey("exeWebServiceCall2") as? Bool

    if (exeWebServiceCall2 == true){

    var temasArray:[String] = ["Word","PowerPoint","Excel"]
    var subTemasArray: [String] = ["Introduccion","Tema 1","Tema 2"," Tema 3"]

    //Guardar temas y subtemas adquiridos de mi web service a mi grafo de objetos de coreData
    var cantidadCursos = cursos.count
    var indexCursos = 0
    var cantidadTemas = temasArray.count
    var indexTemas = 0
    var cantidadSubTemas = subTemasArray.count
    var indexSubTemas = 0


      var error: NSError?

    do{//para cada uno de mis cursos
        var cursoActual = cursos[indexCursos]

        do{//agregar un objeto entity Tema(que contiene un arreglo con los temas)

        let temaEntity = NSEntityDescription.entityForName("Tema", inManagedObjectContext: managedContext)
        let temaActual = Tema(entity: temaEntity!, insertIntoManagedObjectContext: managedContext)
        temaActual.nombre = temasArray[indexTemas]

            //Inserto todos los temas a mi curso Actual
            var temas = cursoActual.temas.mutableCopy() as NSMutableOrderedSet
            temas.addObject(temaActual)
            cursoActual.temas = temas.copy() as NSOrderedSet

                 do{

                let subTemaEntity = NSEntityDescription.entityForName("SubTema", inManagedObjectContext: managedContext)
                let subTemaActual = Tema(entity: subTemaEntity!, insertIntoManagedObjectContext: managedContext)
                subTemaActual.nombre = subTemasArray[indexSubTemas]

                //Inserto todos los subTemas a mi tema Actual
                var subTemas = temaActual.subTemas.mutableCopy() as NSMutableOrderedSet
                subTemas.addObject(subTemaActual)
                temaActual.subTemas = subTemas.copy() as NSOrderedSet

                    //Guardar, aunque no estoy seguro si puedo usar el mismo managedContext que ya tenia
                    if !managedContext.save(&error)
                      {
                            println("No pude guardar: \(error)")
                      }

                       indexSubTemas++
                    }while(indexSubTemas < cantidadSubTemas)

               //reset index subtemas  y aumento indexTemas para el siguiente ciclo de temas
              indexSubTemas = 0
             indexTemas++
           }while(indexTemas < cantidadTemas)
        //reset index temas  y aumento indexCursos para el siguiente ciclo de cursos
        indexTemas = 0
        indexCursos++
    }while(indexCursos < cantidadCursos)


        defaults.setBool(false, forKey: "exeWebServiceCall2")
        defaults.synchronize()


    }


}

回答1:


The temas property is a NSOrderedSet, and the subscript [0] returns the type AnyObject. So (as already said in a comment) you have to cast the AnyObject to the actual type

let curso = cursos[index]
println(curso.nombre)
let firstTema = curso.temas[0] as Tema
println(firstTema.nombre)
let firstSubTema = firstTema.subTemas[0] as SubTema
println(firstSubTema.nombre)

Note that you can simplify your loop using for - in:

for curso in cursos {
    // ...
}

and recursively enumerating all objects would look like

for curso in cursos {
    println(curso.nombre)

    for tema in curso.temas.array as [Tema] {
        println(tema.nombre)

        for subtema in tema.subTemas.array as [SubTema] {
            println(subtema.nombre)
        }
    }
}


来源:https://stackoverflow.com/questions/27930542/why-i-cant-access-my-3rd-level-coredata-data-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!