Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ios - Realm Cleaning Up Old Objects

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...