Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete objects in Realm?

Tags:

ios

realm

Deletion in Realm seems to be incredibly underdocumented ... or am I missing something? How do you delete objects from Lists? Where are the examples?

I have object A with a List. I have another object B also with a List C has a reference back up to its parent A

I want to delete a B and all its sub-objects C. If I delete a C I want to remove it from its parent collection A as well.

I am stumped ... and find it unbelievable that Realm docs provide only two examples:

try! realm.write {
  realm.delete(cheeseBook)
}
try! realm.write {
  realm.deleteAll()
}
like image 450
poundev23 Avatar asked Sep 20 '16 01:09

poundev23


People also ask

How to delete Data from realm Database?

Navigate to the app > res > layout > activity_update_course. xml file and add a Button inside this layout for deleting a course.

How to clear realm db android?

try { Realm. deleteRealmFile(getActivity()); //Realm file has been deleted. } catch (Exception ex){ ex. printStackTrace(); //No Realm file to remove. }

How do you delete a class on realm?

To delete an object from a realm: Right-click (or control-click) the object you want to delete, and select Delete selected object. You'll see a dialog asking you to confirm the action. Press the Delete selected object button to confirm.


1 Answers

First off the bat, you shouldn't ever need to manually implement a reference from a child back up to its parent. Realm implements an inverse relationship feature that lets children objects automatically look up which objects they belong to.

class C: Object {
    let parent = LinkingObjects(fromType: A.self, property: "c")
}

Realm does not support cascading deletes yet (There's an issue for it here ) so it's not enough to simply delete a top level object and expect any objects in List properties of that object to also get deleted. It's necessary to capture those objects directly, and manually delete them before you then delete its parent.

let childObjects = b.subObjects
try! realm.write {
    realm.delete(childObjects)
    realm.delete(b)
}

(That SHOULD work, but if it doesn't, copy all of the sub-objects to a normal Swift array instead and do it from there)

If you delete an Object outright, it will also be removed from any List instances, so deleting C should remove its reference in A automatically.

Sorry you're having trouble! I've logged an issue suggesting that the documentation on deleting objects from Realm is reviewed and improved. :)

like image 195
TiM Avatar answered Nov 09 '22 12:11

TiM