0

When I try to save the data during the App to use after restarting, I found by mistake when saving to NSUserDefault that I can't save directly with Structs, according to what I read NSUserDefaults can only save a small set of types: NSData, NSString, NSNumber , NSDate, NSArray containing only these types, or NSDictionary containing only these types, but I found some forms in C, which I'm not familiar with, and some in Swift but I do not quite understand,besides I can't find the way to do it with Struct "Carreras" that is embedded in the Struct "CursosG". I'm looking for an effective way to be able to run this in Swift 3. This is my code:

struct CursosG {
    let id: Int
    let nrc: String
    let profesor: String
    let carreras: [Carreras]
    let dia: String
    let bloque: String
    let sala: String
    let idcurso: Int
    let comentario: String
    let curso: String

    init(id: Int, nrc: String, profesor: String, carreras: [Carreras], dia: String, bloque: String, sala: String, idcurso: Int, comentario: String, curso: String) {
        self.id = id
        self.nrc = nrc
        self.profesor = profesor
        self.carreras = carreras
        self.dia = dia
        self.bloque = bloque
        self.sala = sala
        self.idcurso = idcurso
        self.comentario = comentario
        self.curso = curso
    }    

    struct Carreras {
        let id: Int
        let nombre: String
        let semestre: Int

        init(id: Int, nombre: String, semestre: Int) {
            self.id = id
            self.nombre = nombre
            self.semestre = semestre
        }
    }
}

...

var CursoAllG = [CursoG]()

...

let curso = CursosG(id: idT, nrc: nrcT, profesor: profesorT, carreras: carrers as! [CursosG.Carreras], dia: diaT, bloque: bloqueT, sala: salaT, idcurso: idcursoT, comentario: comentarioT, curso: cursoT)
CursosAllG.append(curso)

...

UserDefaults.standard.set(CursosAllG, forKey: "cursosAllG")

How should I convert the struct?

  • Have you thought about CoreData rather than UserDefaults? Storing objects in UserDefaults can be messy, and CoreData isn't designed to store multiple of a single type of object (if say you want to store 10+ CursoG objects). While you could serialize CursoG and Carrera for storage in UserDefaults, this may not be the best way depending on your requirements. – Michael Fourre Feb 05 '17 at 07:56

1 Answers1

0

You need to convert your struct data to NSData and then you will be able to store it. Here is a so link which describes it Structs to NSData to Structs?

However I still feel you should use a dictionary instead of using structs as it has cross platform support.

Community
  • 1
  • 1
manishg
  • 9,520
  • 1
  • 16
  • 19