Caching Data in Swift from a Realm Object?

Hey everyone, I’ve hit a wall with figuring out NSCache in conjunction with Realm. Basically, I have a function for opening up the Realm and storing results from some Plant objects, and that works great. Additionally, I was able to set up another model for caching Image URLs, and I’m able to pass through a URL string from the Plant object retrieved from Realm just fine.

The problem is, I can’t seem to figure out how to cache ALL the data from the Realm Object once it’s called - right now, everything’s based on EnvironmentObject/Observable Object, so every single time the view is accessed, the Realm function shoots off and it takes a few seconds to propagate even 5 documents from Realm. I’d like to avoid that by caching objects altogether.

Would this require shifting data from the ObservableObject Realm Object into CoreData? I’d like to avoid that and stick with NSCache if possible, but would love any advice on the matter!

NSCache is probably not the right solution. More importantly, where are the images actually being stored?

What would you recommend for caching the actual object content? NSCache is recommended commonly for images, as it’s thread-safe and removes items from cache when memory is needed by other apps - the images are called via a URL link (hosted by another site), and then stored locally on the device.

I was more asking what process you’re using to work with the images. e.g. you have a Realm Object that a url property? Or you’re using NSData to actually store the data in Realm itself? If they are stored locally, do you need to cache them?

Ah so it’s a URL property within the Realm Object that’s called through a URLSession. Once the URL is accessed, I pass it through a URLImageModel that then loads the image and caches the image itself locally. Check out the pastebin for the model here: Pastiebin.com 5f49448078708

I feel like I have to do something similar with the above model and key in the other properties/data from the Realm Object and cache it similarly?

That’s going to be hard to say without understanding the entire use case.

However, Realm is an offline-first database so there would not be any reason to cache the Realm objects since they are locally stored anyway. Additionally, the Realm objects are lazily loaded so the memory impact of a Results object is minimal - again, no cache’ing would be needed.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.