What's the issue
I am trying to save an instance of a customized Swift Enum that contains Associated Values for each Enum cases to the NSUserDefault. The reason for s it is because the associated values are referencing to some objects that need to be reused when the app get relaunched, which means those objects that get referenced to are custom objects that need to get aware of by the app when it got launched.
Example
class ABCModeController {
static var sharedInstance = ABCModeController()
enum ABCMode {
case On([ABCMachine], Int?, UIColor?)
case Off([ABCMachine])
case Toggle([ABCMachine], Int?, UIColor?)
}
var customMode1:ABCMode?
var customMode2:ABCMode?
var customMode3:ABCMode?
}
What's the expected behavior
From the above example, the Swift Enum gets wrapped in a singleton class it is expected that each instance of ABCMode, which are the customMode1, customMode2, customMode3, can get saved into the userDefault when it gets "didSet" its value. And when the app gets relaunched, the userDefault will restore each instance of those ABCMode in this singleton class.
What's tried & potential solutions
- The Swift Enum can set rawValue to itself, while I found that setting rawValue as Int and String did not solve the problem yet, and I wonder if we can set any object as the rawValue of the Enum? If this can be a solution, how to make the rawValue contained the associated value of each Enum cases?
- I wonder if The Swift Enum can get converted into NSData for saving to the userDefault?
- Is utilizing NSCoding a better solution for it?
What to ask for
- How to save the Swift Enum that contains Associated Values to the NSUserDefault?
- Is there a better solution for addressing the same issue as described above?
What System & Tool that is in-use
- Xcode 8.3
- Swift 3
- iOS 9.0 & above
Thank you very much.