Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a auto increment key in Realm?

Tags:

ios

realm

I have a unique msgid for each ChatData object.

@interface ChatData : RLMObject @property NSInteger msgid; .... @end 

But each time I create a new object I have to query all objects and get the last msgid.

RLMArray *all = [[ChatData allObjects] arraySortedByProperty:@"msgid" ascending:YES]; ChatData *last = [all lastObject]; ChatData *newData = [[ChataData alloc]init]; newData.msgid = last.msgid+1; 

Is there an efficient way to replace this implementation?

like image 210
drinking Avatar asked Oct 08 '14 08:10

drinking


1 Answers

Realm doesn't have auto increment behavior, so you'll need to manage that yourself. A question I'd encourage you to ask yourself about your data:

Is it necessary to have sequential, contiguous, integer ID's?

If not, then a unique string primary key might be sufficient. Then you can use something like [[NSUUID UUID] UUIDString] to generate unique string ID's. The nice thing about this is that these UUID's are more or less guaranteed to be unique, even in multithreaded scenarios.

If so, it might be more efficient to always keep the last number in memory, so that queries aren't required every time a new ID should be generated. If objects might be created in multiple threads, make sure to make your nextPrimaryKey() function thread-safe, otherwise it might generate the same number twice (or more!).

like image 181
jpsim Avatar answered Sep 22 '22 08:09

jpsim