Search code examples
iosswiftrealmprimary-keyedit

In IOS Realm Primary key, how to update data and if already exist it should not take twice?


With that primaryKey offerName how to avoid repeating of data twice or more time.

when we use didSelectRowAt of that object how to edit it and update the data to its object, Not to take it as new object when we updated.

How can i do it?

import Foundation
import RealmSwift

class Discount: Object {

    @objc dynamic var offerName : String = ""
    @objc dynamic var percentage: Float = 0.00
    @objc dynamic var segmentIndex : Int = 0
    @objc dynamic var dateWise: Date?


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

}

Solution

  • Realm provides several ways to update an objects properties.

    A lot of this answer depends on the use case - for this example, it appears you are trying to update the property of a known object than has an existing primary key.

    Starting with a DiscountClass - one thought is that offerName will probably not be a good primary key; what if you have two offers with the same name '10% Off' is common. You're better to use a UUID and then have the offer as text within the object.

    class DiscountClass: Object {
        @objc dynamic var discount_id = UUID().uuidString //guaranteed unique
        @objc dynamic var offerName : String = ""
        @objc dynamic var percentage: Float = 0.00
        override class func primaryKey() -> String? {
            return "discount_id"
        }
    }
    

    Based on your question it looks like those are presented in a list (tableView?) which would be backed by a dataSource, usually an array or for Realm, a Results object which works as well.

    var discountResults = Results<DiscountClass>
    

    When a user selects a row to edit, that row index will correspond to the index in the discountResults. I don't know how you are editing so lets just say that when the user selects a row, they can then edit the percentage. When they are done the update is super simple

    try! realm.write {
        thisDiscount.percentage = "0.1" //updates this objects percent to 10%
    }
    

    Since it's a known object you are specifically updating that objects percentage and it will not create another object.

    If you're in a situation where you may be adding a new object instead of updating an existing one then you can leverage using the realm.create option and supply either .modified or .all to the update parameter. Noting that .all can have a LOT of overhead so generally .modified is preferred.

    Keeping in mind that to use realm.create, you need to create the object and assign an existing primary key if you want to update, or a new unique primary key if you want to create.

    See the documentation for more example and complete explanation: Updating objects with primary keys