Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm Cleaning Up Old Objects

Tags:

ios

realm

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?

like image 568
Brandon Schlenker Avatar asked Nov 10 '15 22:11

Brandon Schlenker


People also ask

How do you delete an object in a realm?

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.

How do I delete all data from a realm?

The right way of deleting your entire Realm (schema) is to use : Realm realm = Realm. getDefaultInstance(); realm. beginTransaction(); // delete all realm objects realm.


1 Answers

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!

like image 79
TiM Avatar answered Sep 25 '22 02:09

TiM