Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to store struct in NSCache

Is there any way to store struct values in NSCache ? When I read the apple documentation look like you can only store AnyObject to it. There are couple of work around one is convert sturct to class, second convert sturct values to the dictionary but they are very expensive operation if dataset is big. Any suggestion?

like image 287
AAV Avatar asked Oct 22 '15 13:10

AAV


People also ask

Where is NSCache stored?

The data stored for those cells are kept by NSCache, which stores data in-memory, so it's readily accessible by RAM.

When to use NSCache?

You typically use NSCache objects to temporarily store objects with transient data that are expensive to create. Reusing these objects can provide performance benefits, because their values do not have to be recalculated. However, the objects are not critical to the application and can be discarded if memory is tight.

What is an efficient way to cache data in memory Swift?

Avoiding stale data What makes NSCache a better fit for caching values compared to the collections found in the Swift standard library (such as Dictionary ) is that it'll automatically evict objects when the system is running low on memory — which in turn enables our app itself to remain in memory for longer.


1 Answers

I'm going to chance my arm on a 'no' (without workarounds). NSCache is resoundingly over on the Objective-C side of the runtime, written to work with NSObjects, bridged via AnyObject. Unlike NSDictionary and NSArray there is no equivalent Swift collection that the compiler can bridge between.

Implementation points aside: NSCache simply doesn't live in a world that understands value semantics for anything more sophisticated than C atoms.

That being said, probably the easiest workaround is just to create an object container for your struct, making the bridging explicit but owned by whomever wants to use the cache:

class YourStructHolder: NSObject {
    let thing: YourStruct
    init(thing: YourStruct) {
        self.thing = thing
    }
}

cache.setObject(YourStructHolder(thing: thing), forKey:"Whatever")
(cache.objectForKey("Whatever") as? YourStructHolder)?.thing

... or skip the init and use a var ...: YourStruct? if you're happy with mutability. You're going to have to deal with optionality when talking to the cache anyway.

like image 184
Tommy Avatar answered Sep 23 '22 07:09

Tommy