Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

ios - How do I set a auto increment key in 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?

question from:https://stackoverflow.com/questions/26252432/how-do-i-set-a-auto-increment-key-in-realm

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...