Save object to a Swift(IOS) session

Asked

Viewed 263 times

0

I have a class and a subclass inside

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?

  • You need to make your class conform to Nscoding http://stackoverflow.com/documentation/swift/5360/nscoding/19088/nscoding-compliant-class#t=2016081100544457751

  • if it is to pass this data between sequential screens you can pass via screen startup parameters (init)

  • I could demonstrate what that code would look like because I have a subclass Enrollment within the Student class

  • http://stackoverflow.com/a/33194374/2303865

  • So in this example the attributes of your class are all String, as would the code with a class that has another class as attribute??

2 answers

1


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

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

In implementing this protocolon, the same 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 salvage the object

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

To carry 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
}

0

If what you want is to retrieve the object in another view, use the NSUserDefaults is not the best way. Try passing it by setting the object in the next view by 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 asynchronous response of the Alamofire when mounting the object. If this is your problem, you can call the next view only after you receive the answer (push the view into the request block) or you can create a callback to receive the asynchronous response.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.