Swift 2.1 :
import Foundation
class Goal : NSObject, NSCoding {
var title: String
init(title: String) {
self.title = title
super.init()
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(title, forKey: "GoalTitle")
}
required convenience init?(coder aDecoder: NSCoder) {
guard let unarchivedGoalTitle = aDecoder.decodeObjectForKey("GoalTitle") as? String
else {
self.init(title: "unknown")
return
}
self.init(title: unarchivedGoalTitle)
}
}
and you should use it in your view controller, as in this test code:
// create an array with test data
let goal1 = Goal(title: "first goal")
let goal2 = Goal(title: "second goal")
let goalArray = [goal1, goal2]
// first convert the array of custom Goal objects to a NSData blob, as NSUserDefaults cannot handle arrays of custom objects directly
let dataBlob = NSKeyedArchiver.archivedDataWithRootObject(goalArray)
// this NSData object can now be stored in the user defaults
NSUserDefaults.standardUserDefaults().setObject(dataBlob, forKey: "myGoals")
// sync to make sure they are saved before we retreive anytying
NSUserDefaults.standardUserDefaults().synchronize()
// now read back
if let decodedNSDataBlob = NSUserDefaults.standardUserDefaults().objectForKey("myGoals") as? NSData {
if let loadedGoalsArray = NSKeyedUnarchiver.unarchiveObjectWithData(decodedNSDataBlob) as? [Goal] {
for goal in loadedGoalsArray {
print("goal : \(goal.title)")
}
}
}
As a final note: it would be easier to use NSKeyedArchiver instead of NSUserDefaults and store an array of custom objects directly in the file. You can learn more about the difference between the two methods in another answer that I posted here .
source
share