62

对Realm数据库多线程下被调用的处理

 5 years ago
source link: http://www.cocoachina.com/ios/20190329/26687.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Realm是一个非常方便的数据库,但是也有其局限性。正如Realm官方文档所述:

Threads

Although Realm files can be accessed by multiple threads concurrently, you cannot hand over Realms, Realm objects, queries, and results between threads.

虽然每个线程都能取到Realm文件,但是这些文件并不能在线程间通信。当你取出一个RealmObject,若想使用其最新数据,需要调用[RLMRealm refresh]方法,或者将RLMRealm的autorefresh参数设为YES。

而官方文档提到:

Realms are automatically refreshed at the start of every runloop iteration

autorefresh让Realm在每个runloop循环开始的时候自动刷新,所以一般不推荐设置为自动刷新。

[RLMRealm commitWriteTransaction]方法被调用的时候Realm数据也将被刷新。

所以在一个类调用Realm数据时,可以这样处理:

- (RLMObject *)RLMObj {  @synchronized (RLMObj) {      if (!_RLMObj || _RLMObjTread != [NSThread currentThread]) {
          [[RLMRealm defaultRealm] refresh];
          _RLMObjTread = [NSThread currentThread];
          _RLMObj = [RLMObj objectsWhere:@"pid = '12345"];
      }      return _RLMObj;
   }
}

使用一个变量存储当前Realm对象的线程,当线程不一致时,刷新数据库重取,即可在多线程的情况下愉快的使用Realm数据库

附上Realm关于线程的官方文档: https://realm.io/docs/objc/latest/#threading


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK