ThuongNM
ThuongNM

Reputation: 25

Swift iOS How to store custom type object locally?

I have created a struct data type. Like below

struct MyType {
var a:String
var b:String
}

After that I get JSON data (use Alamofire) from my server and parse to object (by SwiftyJSON. Now, I'd like to store my parsed object locally. I have tried Haneke library but it was complicated. Could you teach me any way to do it, thank you very much.

Upvotes: 0

Views: 1190

Answers (3)

PiterPan
PiterPan

Reputation: 1802

For this kind of operation the best way to do it is use CoreData or Realm. In this case you can create your own Object and save it in data base. In Realm it takes you ca. 1 min to do it. It looks like that:

 class MyType: Object {
    dynamic var a: String?
    dynamic var b: String?
}

then for example in ViewController you can save this object calling this code:

let realm = try! Realm()
try! realm.write{
    realm.add(MyType)
}

that is all. Simple and easy.

Upvotes: 1

Fujia
Fujia

Reputation: 1242

I think you want to store structured data(objects) locally. Archive objects into raw data and store it as file would meet your needs. Check out the offical guide on how to serialize objects.

Upvotes: 0

Sumit Jain
Sumit Jain

Reputation: 156

-If you want to save the information even after you kill the app: Then save the JSON string in NSUserDefaults. And whenever you need it, just get it back from NSUserDefaults and convert it into your Model Class/Struct.

  • If you just want the info to be saved until the app is alive: Create a custom session class, and save the model there. But in this case, you have to set the model every time you open the app.

Sometimes I set data in AppDelegate class.

Upvotes: 0

Related Questions