Save object in a session in Swift (IOS)

0

I have a class and inside a subclass

import Foundation
import ObjectMapper

class Aluno: Mappable
{
    var ra:String!
    var senha:String!
    var nome:String!
    var cpf:String!
    var email:String!
    var matricula:Matricula!

    required init?(_ map: Map) {}


    func mapping(map: Map) {
        ra          <- map["Ra"]
        senha       <- map["Senha"]
        nome        <- map["Nome"]
        cpf         <- map["Cpf"]
        email       <- map["Email"]
        matricula   <- map["Matricula"]
    }
}


import Foundation
import ObjectMapper

class Matricula: Mappable
{
    var turma:String!
    var turno:String!
    var curriculo:String!
    var curso:Curso!
    var instituicao:Instituicao!

    required init?(_ map: Map) {}


    func mapping(map: Map) {
        turma       <- map["Turma"]
        turno       <- map["Turno"]
        curriculo   <- map["Curriculo"]
        curso       <- map["Curso"]
        instituicao <- map["Instituicao"]
    }
}

After filling this object with a return from a JSON

Alamofire.request(.GET, urlBase, parameters: ["ra": idDoAluno, "senha": senhaDoAluno])
                .responseJSON { response in
                    let JSON = response.result.value as! NSDictionary;

                    self.aluno = Mapper<Aluno>().map(JSON["Dados"]!)!

How do I save this Student object within a session (NSUserDefaults) to retrieve it in another view?

    
asked by anonymous 11.08.2016 / 02:45

2 answers

1

To save custom objects to NSUserDefaults you need to make the class of that object implement the protocole NSCoding .

class Aluno: Mappable, NSCoding {
    // código aqui
}

When you implement this protocolo , it will require you to implement two functions:

required init(coder aDecoder: NSCoder) {
    if let ra = aDecoder.decodeObjectForKey("Ra") as? String {
        self.ra = ra
    }
    // Preencher todos os outros atributos, fazendo o cast para o tipo correspondente
}

func encodeWithCoder(coder: NSCoder) {
    if let ra = self.ra {
        aCoder.encodeObject(ra, forKey: "Ra")
    }
}

To save the object

func saveAluno(aluno: Aluno) {
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(NSKeyedArchiver.archiveDataWithRootObject(aluno), forKey: "aluno")
    defaults.synchronize()
}

To load the object

func loadAluno() -> Aluno? {
    let defaults = NSUserDefaults.standardUserDefaults()
    if let data = defaults.objectForKey("aluno") as? NSData {
        return NSKeyedUnarchiver.unarchiveObjectWithData(data) as! Aluno
    }
    return nil
}
    
24.08.2016 / 20:52
0

If you want to recover the object in another view, using NSUserDefaults is not the best way. Try passing it by setting the object in the next view to prepareForSegue .

Example:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     if segue.identifier == "SendDataSegue" {
        if let destination = segue.destinationViewController as? SecondViewController {
            destination.aluno = meuObjetoAluno 
        }
     }
}

Also beware of the Alamofire's asynchronous response when mounting the object. If this is your problem, you can call the next view only after receiving the response (put the view push inside the request block) or you can create a callback to receive the asynchronous response.

    
22.08.2016 / 16:26