Reputation: 117
I have 2 classes (Client, Admin) that inherit from the same parent class (User).
Those 3 classes implement the NSCoding protocol so I can store them in the userdefaults as Data.
When my application starts I want to deserialized the stored Data into Swift objects.
Is there a way to know which type the stored Data belongs to?
something like this:
let data = defaults.object(forKey: "loggedInUser") as? Data
if data is Client
let client = NSKeyedUnarchiver.unarchiveObject(with: data) as? Client
if data is Admin
let admin = NSKeyedUnarchiver.unarchiveObject(with: data) as? Admin
Upvotes: 1
Views: 264
Reputation: 2327
You can check
if let data = defaults.object(forKey: "loggedInUser") as? Data {
let obj = NSKeyedUnarchiver.unarchiveObject(with: data)
if obj is Client {
let client = obj as! Client
}
if obj is Admin {
let admin = obj as! Admin
}
}
Upvotes: 1