Can Only Delete an Object from the Realm It Belongs To ? Oh,, What? — Swift

Muhammad Muizzsuddin
2 min readMar 6, 2018

--

Visit https://mozzlog.com for more article about engineering for mobile, web, and backend.

You can also use my custom made app. 🚀 https://tomioai.com/

That serious problem comes to me just recently. What cause it to happen which makes my application hang up and terminates unexpectedly is that really obscure at first. You can imagine that when it is your first application, first Realm usage, and it terminates without clear explanation, although the error says as what stated in title, that still makes me confused.

Here is the code that causing error.

// Suppose I have RMProduct: Objectclass ProductRepository {
let realm = // Instantiate Realm Object
func fetch(predicate: NSPredicate) -> [Product]? {
return realm.objects(RMProduct.self)
.filter(predicate)
}

func add(_ product: RMProduct) {
try! realm.write {
realm.add(product, update: true)
}
}
func delete(_ product: RMProduct) {
try! realm.write {
realm.delete(product)
}
}

That delete function causing error because the object I was sent isn’t match to the object in Realm. What is that mean?

Somewhere in the application. I mutate the object, copying and somewhere do some operation that causing the object becomes a foreign object for Realm. Actually, whenever the Realm object is passing outside the realm transaction, that will be a copy of the Realm object and becomes a foreigner. To prevent unexpected behavior, it’s better to refer the object directly to the Realm disk.

What I should to do in the next is just refrerring the object I want to delete to to the object in Realm disk.

Here is the code to do that such action. This code is inside Realm transaction in the delete function.

let predicate = NSPredicate(format: "UUID == %@", product.uuid)if let productToDelete = realm.object(RMProduct.self)
.filter(predicate).first {
realm.delete(productToDelete)
}

That’s all. So now I refer to the object/ product inside Realm disk and it says, “Oh yeah. I want to delete this object. Thanks for the clear information. Have a nice day!”

[PS : If you have better solution or explanation, please to comment below. Or email me at m.muizzsuddin @ gmail.com]

--

--

Responses (1)