22

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>
}
Voyager
  • 399
  • 1
  • 8
  • 15

8 Answers8

36

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)
Chris Byatt
  • 3,689
  • 3
  • 34
  • 61
fel1xw
  • 576
  • 4
  • 7
11

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)
}
William Hu
  • 15,423
  • 11
  • 100
  • 121
9
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)")
    }
}
BatyrCan
  • 6,773
  • 2
  • 14
  • 23
4

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
}
Diogo Antunes
  • 2,241
  • 1
  • 22
  • 37
3

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

Dmitry
  • 7,300
  • 6
  • 32
  • 55
3
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)")
    }
Ashish
  • 706
  • 8
  • 22
0

There is an easier option to remove 1 object:

$item.delete()

remember to have the Observable object like:

@ObservedRealmObject var item: Items
Arturo
  • 3,254
  • 2
  • 22
  • 61
0
var realm = try! Realm()

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

    
}
Iva
  • 2,447
  • 1
  • 18
  • 28
  • 1
    Welcome to Stack Overflow! FYI your answer has been flagged as low quality by the system because it contains no text, please add a short description for what your code does. – chantey Jul 25 '22 at 22:39