Reputation: 3246
I have a struct that's something like the following:
Struct User {
let name: String?
let address: String?
init(name: String, address:String) {
self.name = name
self.address = address
}
}
I'm trying to cache the users profile but I'm in doubt on the best approach to do it.
The struct example I gave above is a smaller size of my real struck which containes profile picture as well.
I already cache some useful stuff in [UserDefaults] but I'm wondering if I should cache the user profile inside UserDefaults or CoreData?
If you think UserDefaults is the best approach, how can I store this Class-type into it? I can store simple booleans and so on, but how could I save a struct like the above, then fetch its data properly?
self.cacheUser = User(name: "Ivan", address: "EUA")
How could I cache the [cacheUser] into [NSUserDefaults] ?
Thanks.
Upvotes: 0
Views: 72
Reputation: 3557
You can use an NSKeyedArchiver
to archive the object and then an NSKeyedUnarchiver
to unarchive the object, but it would have to conform to the NSCopying
protocol.
You can also use CoreData
to save the objects if they are more extensive and complex.
If there are not too many variables in the classes, you can simply put the variable names and values in a dictionary and save the dictionary to your user defaults. You can then fetch them and rebuild the object with the dictionary values saved in user defaults. But I would only do this if the objects are very simple (eg, a class with a couple Ints and/or Strings).
Ultimately, I suggest using CoreData
for persisting custom objects. Because, as classes begin to get more and more complex, CoreData
will give you much better performance and faster accessibility.
Upvotes: 1