0
我知道其他人問過這個問題,但是,我正在努力在我自己的項目中實現該解決方案。我正在爲學校創建一個計劃應用程序,並且我想將用戶的類存儲在一個ClassInfo對象的數組中。下面是創建該對象我的ClassInfo類:使用Swift存儲自定義對象數組3
class ClassInfo: NSObject {
var name = String()
var room = String()
var period = Int()
init(name: String, room: String, period: Int) {
self.name = name
self.room = room
self.period = period
}
required init(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObject(forKey: "name") as! String
self.room = aDecoder.decodeObject(forKey: "room") as! String
self.period = aDecoder.decodeObject(forKey: "period") as! Int
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.name, forKey: "name")
aCoder.encode(self.room, forKey: "room")
aCoder.encode(self.period, forKey: "period")
}
}
以我初始視圖控制器,I創建類陣列是這樣的:
var classes = [ClassInfo]()
let defaults = UserDefaults.standard
這是我的代碼,用於將一類到所述陣列:
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?
最後,我想將數組中的類放入UITableView中。這裏是我迄今爲止做的代碼:
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
}
基本上,我只是想利用具有類的名稱,週期和房間號我的自定義的ClassInfo對象來保存用戶的類。