0

I currently have the following Codabledata 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.

  • Result in error? What error? How did you saved your data in UserDefaults? Did you used a JSONEncoder? Alsoe, `xcdatamodel` is more for CoreData (which isn't your case). – Larme Jan 27 '21 at 09:49
  • "Codable + UserDefaults" in your favorite SEO: https://www.hackingwithswift.com/example-code/system/how-to-load-and-save-a-struct-in-userdefaults-using-codable https://stackoverflow.com/questions/44876420/save-struct-to-userdefaults https://stackoverflow.com/questions/51697001/saving-a-codable-struct-to-userdefaults-with-swift What went wrong with that code? – Larme Jan 27 '21 at 10:02
  • @Larme I used those links and updated my question above – Aneesh Poddutur Jan 27 '21 at 12:50

2 Answers2

0
Data Save:
    var userDefaults = UserDefaults.standard
    let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: 
    EventDataArray)
    userDefaults.set(encodedData, forKey: "EventDataArray")
    userDefaults.synchronize()

Data Read:
    let decoded  = userDefaults.data(forKey: "EventDataArray")
    let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded) 
    as! [EventDataArray]

You get the more answers to this link Save custom objects into NSUserDefaults

Mahbeer
  • 1
  • 1
  • 1
0
struct UserInfo: Codable {
    var name: String
    var emailId: String
    var dob: String
    var city: String
    var study: String
}
  • save data to UserDefault

    if let userInfo = try? JSONEncoder.encode(self.UserInfo) {
      UserDefaults.standard.set(userInfo, forKey: "UserInfo")  }
    
  • retrive data from UserDefault

     if let retriveData = UserDefaults.standard.object(forKey: "UserInfo") as? Data {
     if let userdata = try? JSONDecoder().decode(UserInfo.self, from: retriveData) {
         print(userDetails)
     }}
    
sid_patel_1211
  • 151
  • 1
  • 7