2

I have a class say,

class GroupClass{
    var groupId: String = ""
    var groupName: String = ""
}

I want to be able to store its object in NSUserDefaults. I tried this way,

let group = GroupClass()
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(group, forKey: "group")
defaults.synchronize()

and retrieved it following way,

let defaults = NSUserDefaults.standardUserDefaults()        
var group = defaults.objectForKey("group") as! GroupClass

It threw exception Using non-property obect and crashed. What is the right way to do it in Swift?

Also tried the following way,

class GroupClass{
    var groupId: String = ""
    var groupName: String = ""

    required init(coder aDecoder: NSCoder) {
        self.groupId = aDecoder.decodeObjectForKey("groupId") as! String
        self.groupName = aDecoder.decodeObjectForKey("groupName") as! String

    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.groupId, forKey: "groupId")
        aCoder.encodeObject(self.groupName, forKey: "groupName")

    } 
}

But, let group = GroupClass(coder:NSCoder()) gives problem.

Dark Drake
  • 360
  • 1
  • 8
  • 21

1 Answers1

2

You can't save class reference to userdefault. group is your reference of your class. why you are saving it. it just points your class in memory. it will be destroy after completing it's task. userdefaults are for storing data like strings, arrays, dictionary etc. you should not need to store reference in database. i don't think so.

you can set group.groupId or group.groupName in userdefaults. then also if you want to store that then you can convert it in nsdata by NSKeyedArchiver and save that data to nsuserdefault and unarchive it when it needed by NSKeyedUnArchiver.

Hope this will help :)

Ketan Parmar
  • 26,610
  • 9
  • 47
  • 70