poundev23
poundev23

Reputation: 807

How to delete objects in 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()
}

Upvotes: 11

Views: 16011

Answers (2)

Joule87
Joule87

Reputation: 651

There is an implementation of a Realm extension for cascading Deletion in Swift 4. You can find it in GitHub Link ->(https://gist.github.com/verebes1/02950e46fff91456f2ad359b3f3ec3d9). After adding this extension in your code using it will be as simple as placing a flag on the delete method.

realm.delete(object, cascading: true)

Upvotes: 4

TiM
TiM

Reputation: 15991

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. :)

Upvotes: 15

Related Questions