Longshihua
Longshihua

Reputation: 425

What is right way to avoid repeat object save to realm?

Here is my operate order:

1: fetch data from the servers

2: update UI

3: save data to realm

So I have an issue: When I fetch the data again, if the results contain the same data like before, So I don't want to save it to realm again. How can I solve it?

Upvotes: 0

Views: 400

Answers (1)

Johnykutty
Johnykutty

Reputation: 12829

You should create a primary key for your class like

class Foo: Object {
    dynamic var yourPrimaryKey = 0
    dynamic var otherProperty1 = ""
    // and so on

    override class func primaryKey() -> String? {
        return "yourPrimaryKey"
    }
}

Then when you save data

let foo = Foo()
//set properties for foo
realm.add(foo, update: true)

The documentation says:

parameter update: If true, the Realm will try to find an existing copy of the object (with the same primary key), and update it. Otherwise, the object will be added.

Upvotes: 2

Related Questions