Storing an Array of Custom Objects Using Swift 3

I understand others have asked this question, however, I am struggling to implement the solution in my own project. I am creating a schedule app for school, and I want to store the user’s classes in an array of ClassInfo objects. Here is my ClassInfo class that creates the object:

class ClassInfo: NSObject {
var name = String()
var room = String()
var period = Int()

init(name: String, room: String, period: Int) { = name = room
    self.period = period

required init(coder aDecoder: NSCoder) { = aDecoder.decodeObject(forKey: "name") as! String = aDecoder.decodeObject(forKey: "room") as! String
    self.period = aDecoder.decodeObject(forKey: "period") as! Int

func encode(with aCoder: NSCoder) {
    aCoder.encode(, forKey: "name")
    aCoder.encode(, forKey: "room")
    aCoder.encode(self.period, forKey: "period")

In my initial view controller, I create the array of classes like this:

var classes = [ClassInfo]()
let defaults = UserDefaults.standard

This is my code for adding a class to the array:

let c = ClassInfo(name: className.text!, room: roomNumber.text!, period: period.selectedSegmentIndex + 1)
classes.insert(c, at: periodsSelected.index(of: period.selectedSegmentIndex + 1)!)
//How do I actually update the array in UserDefaults?

And finally, I would like to take the classes in the array and put them into a UITableView. Here is the code I have so far to do that:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = Bundle.main.loadNibNamed("ScheduleTableViewCell", owner: self, options: nil)?.first as! ScheduleTableViewCell
    cell.classLabelView.text = "\(classes[indexPath.row].name)"
    cell.classPeriodLabel.text = "\(classes[indexPath.row].period)"
    cell.roomLabel.text = "\(classes[indexPath.row].room)"
    cell.isUserInteractionEnabled = true
    cell.selectionStyle = .none
    return cell

Basically, I just want to save the user’s classes using my custom ClassInfo object which has a class name, period, and room number.

1 answer

  • answered 2017-06-17 19:12 Umar Farooque

    1. How do I actually update the array in UserDefaults?

    You have to replace it with the previously stored value.

    But also since you are making and Array of custom objects, you have to convert it into NSData or Data first and then store it in UserDefaults like:

    UserDefaults.standard.set("ENTER_YOUR_DATA", forKey:"ENTER_YOUR_TAG")
    1. Why are you using NSObject ?

    You could do the same via using structures and save memory, just make the functions mutable to achieve the same functionality.