2

I have a class in my project that queries a private server and returns a human readable username on being given an alphanumeric user ID. I implemented this as a class method.

I don’t want to query the server too much. I know this can be solved by implementing an instance method, but I really just want to use a class method. How can I implement a private cache of the user ID/username pairs, preferably using a NSMutableDictionary?

duci9y
  • 4,128
  • 3
  • 26
  • 42
  • 2
    Why not NSCache? Make it a static variable in your class implementation file and write some class methods that wrap it. – Carl Veazey Jan 12 '13 at 08:38
  • Or make a dictionary static in the class. I didn't get this at first either: http://stackoverflow.com/questions/8432360/can-i-use-a-class-method-to-set-a-static-variable – jrturton Jan 12 '13 at 08:49
  • @CarlVeazey I didn’t even know something like `NSCache` existed. Submit that as an answer and I will accept it. – duci9y Jan 12 '13 at 09:20

1 Answers1

3

I'd suggest using NSCache. Create a static variable inside your class's implementation file. For example:

#import "MyClass.h"

static NSCache *Cache;

@implementation MyClass

+ (void)initialize 
{
    [super initialize];

    Cache = [[NSCache alloc] init];
}

//  Rest of class implementation here

@end

You will want to write some class methods that delegate to NSCache depending on your use case. For example, if you're caching data from network requests, you might write methods like:

+ (void)cacheResponse:(NSData *)response forURL:(NSURL *)URL
{
    [Cache setObject:response forKey:URL];
}

+ (NSData *)cachedResponseForURL:(NSURL *)URL
{
    return [Cache objectForKey:URL];
}

For further reading, I'd suggest reading NSHipster's wonderful article on NSCache.

Carl Veazey
  • 18,392
  • 8
  • 66
  • 81