如何在Realm中设置自动增量键? [英] How do I set a auto increment key in Realm?

查看:103
本文介绍了如何在Realm中设置自动增量键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为每个ChatData对象都有一个唯一的msgid。

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

但每次我创建一个新的对象我必须查询所有对象并获取最后一个msgid。

  RLMArray * all = [[ChatData allObjects] arraySortedByProperty:@ msgstr升序:是]; 
ChatData * last = [all lastObject];
ChatData * newData = [[ChataData alloc] init];
newData.msgid = last.msgid + 1;

有没有一种有效的方法来替换这种实现?

解决方案

Realm没有自动增量行为,因此您需要自己管理。一个问题我建议您自问一下您的数据:



是否需要连续的,连续的整数ID?



如果没有,那么唯一的字符串主键可能就足够了。然后你可以使用类似 [[NSUUID UUID] UUIDString] 的东西来生成唯一的字符串ID。关于这一点的好处是,即使在多线程场景中,这些UUID也或多或少地保证是唯一的。



如果是这样,总是保持这些UUID可能更有效率。内存中的最后一个数字,因此每次生成新ID时都不需要查询。如果可能在多个线程中创建对象,请确保使 nextPrimaryKey()函数成为线程安全的,否则它可能会生成相同的数字两次(或更多!)。 / p>

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?

解决方案

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

这篇关于如何在Realm中设置自动增量键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆