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?
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)
I hope that helped!
来源:https://stackoverflow.com/questions/33641221/realm-cleaning-up-old-objects