领土清理旧物件 [英] Realm Cleaning Up Old Objects
问题描述
我刚开始在我的iOS应用中使用Realm进行缓存。该应用程序是一个商店,商品。当用户浏览商品时,我将这些项目添加到数据库中。但是,由于这些项目不能永久保持可用,因此将它们保留在数据库中超过某一点是没有意义的,比方说24小时。有一段时间后批量过期对象的首选方法吗?或者最好在每个应用程序启动时添加日期属性并查询这些对象?
I've just started using Realm for caching in my iOS app. The app is a store, with merchandise. As the user browses merchandise, I'm adding the items to the database. However, as these items do not stay available forever, it does not make sense to keep them in the database past a certain point, let's say 24hrs. Is there a preferred way to batch expire objects after an amount of time? Or would it be best to add a date property and query these objects on each app launch?
推荐答案
没有默认的缓存过期机制在Realm本身,但就像你说的那样,向每个对象添加一个 NSDate
属性并简单地执行查询以检查date属性较旧的对象是一个相对微不足道的事情。在你的应用程序内定期24小时。
There's no default cache expiration mechanism in Realm itself, but like you said, it's a relatively trivial matter of adding an NSDate
property to each object, and simply performing a query to check for objects whose date property is older than 24 hours periodically inside your app.
这两种语言的逻辑可能看起来像这样:
The logic could potentially look something like this in both languages:
Objective-C
NSDate *yesterday = [[NSDate alloc] initWithTimeIntervalSinceNow:-(24 * 60 *60)];
RLMResults *itemsToDelete = [ItemObject objectsWhere:"addedDate < %@", yesterday];
[[RLMRealm defaultRealm] deleteObjects:itemsToDelete];
Swift
let yesterday = NSDate(timeIntervalSinceNow:-(24*60*60))
let itemsToDelete = Realm().objects(ItemObject).filter("addedDate < \(yesterday)")
Realm().delete(itemsToDelete)
我希望帮忙!
这篇关于领土清理旧物件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!