Reputation: 10589
I have multiple Objects which are not defining a primary key (because our server is handling the primary keys and in offline mode you cant provide a primary key) so i cant use the update
method if i change data, so i tried the following:
func updateTest() {
let myObjects = realm.objects(MyObject.self).filter("id = 1"); // id is NOT the primary key from realm!
var myObject: MyObject!;
if (myObjects.count > 0) {
myObject = myObjects[0];
}
if (myObject != nil) {
try! self.realm.write() {
self.realm.delete(self.myObject);
}
// modify
self.myObject.status = "waiting";
try! self.realm.write() {
self.realm.add(self.myObject); // crash
}
}
}
But when I want to add the object now i get:
Terminating app due to uncaught exception: 'RLMException', reason: 'Object has been deleted or invalidated.'
So several questions here:
Is there any possibility to select only a single result?
Is there any possibility to update an object by providing a field name which is not the primary key?
How can i delete and readd an object without getting this error?
would it maybe make sense to implement a dummy primary key?
Upvotes: 0
Views: 928
Reputation: 18308
What you're trying to do can be accomplished like this:
func updateTest() {
guard let myObject = realm.objects(MyObject.self).filter("id = 1").first else {
return
}
try! realm.write {
myObject.status = "waiting"
}
}
Is there any possibility to select only a single result?
You can use Swift's guard let
to bind the first element in the result set to a variable if one exists, using the else
clause for your fallback if the object cannot be found. In this case I simply return from the function.
Is there any possibility to update an object by providing a field name which is not the primary key?
Yes. Perform a query to locate the object in question, then change its properties however you wish.
How can I delete and readd an object without getting this error?
You cannot delete and re-add an object. There's no way to resurrect a deleted object. It's not necessary to do this to get the behavior you're after.
Would it maybe make sense to implement a dummy primary key?
It's not necessary to get the behavior you're after.
Upvotes: 1