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?
The data stored for those cells are kept by NSCache, which stores data in-memory, so it's readily accessible by RAM.
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.
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.
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 NSObject
s, 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.
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