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.

  • use NSKeyedArchiver for this – Bhavin Bhadani Apr 23 '16 at 10:01
  • @EICaptain Can you please provide a demo code, I am new to Swift. –  Apr 23 '16 at 10:02
  • 2nd answer is in swift http://stackoverflow.com/questions/19720611/attempt-to-set-a-non-property-list-object-as-an-nsuserdefaults – Bhavin Bhadani Apr 23 '16 at 10:02
  • @EICaptain I tried that way `let group = GroupClass(coder:NSCoder())` this gives problem –  Apr 23 '16 at 10:08
  • full solution is in that answer ... check carefully .. there may be some mistake – Bhavin Bhadani Apr 23 '16 at 10:10
  • @EICaptain is this correct way to create object? `let group = GroupClass(coder:NSCoder())` as it says `cannot be sent to an abstract object of class NSCoder: Create a concrete instance!'` –  Apr 23 '16 at 10:13
  • @DarkDrake are you able to solve this question? Can you please upload the solution if you solve this. – ASN Dec 01 '16 at 14:02

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
  • 27,092
  • 9
  • 50
  • 75