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?
Select a realm and click the Edit button. The Edit Realm wizard displays. Click Next to move to the Realm Objects page where you can click Remove to delete objects from the realm. Click Done.
The right way of deleting your entire Realm (schema) is to use : Realm realm = Realm. getDefaultInstance(); realm. beginTransaction(); // delete all realm objects realm.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With