I have object Event with some attributes and a list of users who are attendees of the event:
class Event: Object {
dynamic var eventId:Int = -1
dynamic var type:Int = -1
dynamic var title:String = ""
dynamic var descriptionText:String = ""
dynamic var creatorId:Int = -1
dynamic var owner:User = User()
dynamic var place:String = ""
dynamic var startDate:String = ""
dynamic var lat:Double = 0.0
dynamic var lng:Double = 0.0
dynamic var availability:String = ""
dynamic var attendeesCount:Int = 0
dynamic var attendees = List<User>()
override static func primaryKey() -> String? {
return "eventId"
}
In the first moment in the app, Event is created without any attendees and later, when I want to update it with one or more new attendees event!.attendees.append(attendee), I am having a problem. If the same User as new attendee is already added in database, new one can not be added and the app crashes.
I was also thinking to have another object(table) that will solve this but in that case I will have another issues:
class Attendee: Object {
dynamic var eventId:Int = -1
dynamic var userId:Int = -1
Can somebody give me advice how to solve this, I really want to stay with Realm on this project.
Thanks in advance.
Are you using this event!.attendees.append(attendee) within a write transaction? Can you share the error message and code where you are doing this?
The problem is actually that List.append() will add the object to the Realm if it's unpersisted, but you already have a User with that primary key, so you can't create another User with the same primary key. Instead, you should update the User with the same primary key and append _that_ to the list:
let attendeeValue...
let attendee = realm.create(User.self, value: attendeeValue, update: true)
event!.attendees.append(attendee)
@yoshyosh sure it's inside write transaction closure, I just wrote the most important parts of code to keep my question simple. Error message claims that user with the same id can not be added.
@jpsim thanks for the answer, I will try it out and let you know if it works.
@jpsim it works, thank you!
Most helpful comment
The problem is actually that
List.append()will add the object to the Realm if it's unpersisted, but you already have aUserwith that primary key, so you can't create another User with the same primary key. Instead, you should update the User with the same primary key and append _that_ to the list: