Obj-C: How to make a keyless cache

I am trying to make an object cache to be reused on demand.

This is similar to the UITableViewCell mechanism. When I need a new object, I will get one from the pool (I don't care which one), and if it's not there, I will create a new one that will be cached. When I am done with this, I will put it back into the pool for later use.

NSCache is the most similar class I know, but it is a key / value cache, so that's not exactly what I mean. I don't care what object the cache gives me, I just want to get one (any) from the cache, use it, and then return it back when done.

So what should I use for such a mechanism?

Edit: it doesn't have to be from iOS. I am open to external open source libraries.

Edit 2: I'll give an example for clarification: Let's say I'm trying to create an ant nest (cache): there are about 10,000 ants in the nest.

  • When I need food, I'll take one of the ants and tell him to come out and get food (ant is removed from the cache). I don't care if ant does the job because they are all ants to me. When its task is done, ant will return to the socket and stay there until I give it a new order.
  • If my nest ends up with ant for any reason (the cache is empty), I'll tell the ant queen to propagate some more.
  • If the nest is running out of resources (memory received warning), I want the excessive ants to die on their own (automatic memory management similar to NSCache).
  • If there is no resource crisis, the ants can stay where they are and wait for my order (I am a generous god).
+3


source to share


1 answer


Use NSCache. But you don't want to deal with NSCache keys.

So the Ant class is a subclass of NSObject. Use NSMutableSet storage hash

for each Ant. See the NSObject Protocol Reference for the method hash

.

Use anyObject

to addObject:

dequeue and to assign a hash value from the NSMutableSet. Use hash as parameter for NSCache objectForKey:

.



This saves memory only if the Ant objects are larger than the NSMutableSet from NSUIntegers.

It's easier than trying to create a custom NSMutableSet class with security and automatic NSCache deletion.

+1


source







All Articles