Voyager
Voyager

Reputation: 399

Swift Remove Object from Realm

I have Realm Object that save list from the JSON Response. But now i need to remove the object if the object is not on the list again from JSON. How i do that? This is my init for realm

func listItems (dic : Array<[String:AnyObject]>) -> Array<Items> {
        let items : NSMutableArray = NSMutableArray()
        let realm = try! Realm()
        for itemDic in dic {
            let item = Items.init(item: itemDic)
                try! realm.write {
                    realm.add(item, update: true)
                }
            items.addObject(item)
        }
        return NSArray(items) as! Array<Items>
}

Upvotes: 22

Views: 45495

Answers (8)

Rustem Manafov
Rustem Manafov

Reputation: 41

var realm = try! Realm()

open func DeleteUserInformation(){
        
   realm.beginWrite()
    
   let mUserList = try! realm.objects(User.self)
   realm.delete(mUserList)
    
    
   try! realm.commitWrite()

    
}

Upvotes: 0

Arturo
Arturo

Reputation: 4180

There is an easier option to remove 1 object:

$item.delete()

remember to have the Observable object like:

@ObservedRealmObject var item: Items

Upvotes: 0

Ashish
Ashish

Reputation: 726

do {
        let realm = try Realm()

        if let obj = realm.objects(Items.self).filter("id = %@", newId).first {

            //Delete must be perform in a write transaction

            try! realm.write {
                 realm.delete(obj)
             }
        }

    } catch let error {
        print("error - \(error.localizedDescription)")
    }

Upvotes: 3

BatyrCan
BatyrCan

Reputation: 6983

func realmDeleteAllClassObjects() {
    do {
        let realm = try Realm()

        let objects = realm.objects(SomeClass.self)

        try! realm.write {
            realm.delete(objects)
        }
    } catch let error as NSError {
        // handle error
        print("error - \(error.localizedDescription)")
    }
}

// if you want to delete one object

func realmDelete(code: String) {

    do {
        let realm = try Realm()

        let object = realm.objects(SomeClass.self).filter("code = %@", code).first

        try! realm.write {
            if let obj = object {
                realm.delete(obj)
            }
        }
    } catch let error as NSError {
        // handle error
        print("error - \(error.localizedDescription)")
    }
}

Upvotes: 9

William Hu
William Hu

Reputation: 16151

I will get crash error if I delete like top vote answer.

Terminating app due to uncaught exception 'RLMException', reason: 'Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first.'

Delete in a write transaction:

let items = realm.objects(Items.self)
try! realm!.write {
    realm!.delete(items)
}

Upvotes: 11

fel1xw
fel1xw

Reputation: 576

imagine your Items object has an id property, and you want to remove the old values not included in the new set, either you could delete everything with just

let result = realm.objects(Items.self)
realm.delete(result)

and then add all items again to the realm, or you could also query every item not included in the new set

let items = [Items]() // fill in your items values
// then just grab the ids of the items with
let ids = items.map { $0.id }

// query all objects where the id in not included
let objectsToDelete = realm.objects(Items.self).filter("NOT id IN %@", ids)

// and then just remove the set with
realm.delete(objectsToDelete)

Upvotes: 36

Diogo Antunes
Diogo Antunes

Reputation: 2291

What you can do is assign a primary key to the object you are inserting, and when receiving a new parsed JSON you verify if that key already exists or not before adding it.

class Items: Object {
    dynamic var id = 0
    dynamic var name = ""

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

When inserting new objects first query the Realm database to verify if it exists.

let repeatedItem = realm.objects(Items.self).filter("id = 'newId'")

if !repeatedItem {
   // Insert it
}

Upvotes: 4

Dmitry
Dmitry

Reputation: 7340

The first suggestion that comes to mind is to delete all objects before inserting new objects from JSON.

Lear more about deleting objects in Realm at https://realm.io/docs/swift/latest/#deleting-objects

Upvotes: 3

Related Questions