I currently have the following Codable
data structures:
//Models for Data Handling
struct EventModel: Codable {
let id: UUID
let eventName: String
let fromTime, toTime: Date
let fromTimeString, toTimeString: String
let color: Color
init(id: UUID = .init(),
eventName: String,
fromTime: Date,
toTime: Date,
fromTimeString: String,
toTimeString: String,
color: Color) {
self.id = id
self.eventName = eventName
self.fromTime = fromTime
self.toTime = toTime
self.fromTimeString = fromTimeString
self.toTimeString = toTimeString
self.color = color
}
}
struct Color: Codable {
let (r,g,b,a): (CGFloat,CGFloat,CGFloat,CGFloat)
var color: UIColor { UIColor.init(red: r, green: g, blue: b, alpha: a) }
}
I also have the following Codable
object array in the EventData
class:
//EventData class with EventDataArray
class EventData: Codable {
static var EventDataArray: [EventModel] = []
}
Right now, I have a save button that triggers the following. It creates an instance of the class EventData
and saves it to NSUserDefaults. Since the array is static, all instances should (in theory) hold the same values. The parameters I used (text, fromTime, etc.) were declared previously in the @IBAction
function and were omitted for brevity.
@IBAction func save(_ sender: Any) {
//initialize object
let currentEvent = EventModel(eventName: text, fromTime: fromTime, toTime: toTime, fromTimeString: fromTimeString, toTimeString: toTimeString, color: convertedColor)
//append to data model
EventData.EventDataArray.append(currentEvent)
//write to NSUserDefaults
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(currentEvent) {
let defaults = UserDefaults.standard
defaults.set(encoded, forKey: "SavedEventData")
}
}
This is what I'm confused on. How do I repopulate the array using the static array in the saved data instance?
let defaults = UserDefaults.standard
if let savedEventData = defaults.object(forKey: "SavedEventData") as? Data {
let decoder = JSONDecoder()
if let loadedEventData = try? decoder.decode(EventData.self, from: savedEventData) {
//I'm confused on what to do here.
}
}
I am unable to call the EventDataArray
from the instance loadedEventData
, and get this error when trying to do so Static member 'EventDataArray' cannot be used on instance of type 'EventData'
I would appreciate any help on this issue.