In Realm is there a way to set a unique id for every object stored in the database? I don't necessarily need it to be auto incremented just unique every time. I was just wondering is there a way to do it in Swift 2 on iOS 8 or above? I know you can do it in objC.
Asked
Active
Viewed 2,670 times
1 Answers
3
To generate UUID for all objects in your Realm, you could create a superclass that generates the UUID:
class IdentifiableObject : Object {
private(set) dynamic var uuid = NSUUID().UUIDString
}
Swift5
class IdentifiableObject : Object {
private(set) dynamic var uuid = NSUUID().uuidString
}
While this works, it does come with a major catch, at least until realm supports read-only attributes. When updating objects, you will have to first obtain the stored object before saving.

Anton Tropashko
- 5,486
- 5
- 41
- 66

uɥƃnɐʌuop
- 14,022
- 5
- 58
- 61
-
Be aware that this will cause issues if you are persisting these to a server -- the id's generated in this way are not guaranteed to be unique and could cause collisions. A failsafe way would be to persist to the server on creation and have the server send back an ID. Though this is okay if the id's generated are unique to the user, for example. – Scott Fister Apr 10 '17 at 02:51
-
Indeed, that is correct, but that is not a realm related issue. It's rather the question of how you handle the of syncing objects stored locally and remotely and something you have to consider when working with any type of shared persistence. – uɥƃnɐʌuop Apr 10 '17 at 08:22
-
2@ScottFister I would say that "for there to be a one in a billion chance of duplication, 103 trillion version 4 UUIDs must be generated" is an acceptable risk in many use cases? See https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions – Yvo Jan 26 '18 at 20:23
-
Good to know @Zyphrax, that does seem pretty unlikely :P – Scott Fister Jan 27 '18 at 00:45