Say I have a class method like
+ (double)function:(id)param1 :(id)param2
{
// I want to memoize this like...
static NSMutableDictionary* cache = nil;
//
// test if (param1,param2) is in cache and return cached value, etc. etc
//
}
Thanks!!
If you want to create the cache once and check against it, I generally use an
+initializemethod. This method is called before the first message sent to the class, so the cache would be created before+function::(which, by the way, is a terrible selector name) could be called. In this case, I usually declare the cache variable in the .m file, but declaring it in the method definition may also work.Edit: Adding an example at request of OP:
Obviously, if a value doesn’t exist in the cache, you should have some code that adds the value. Also, I have no idea how you intend to combine
param1andparam2as the key for the cache, or how you’ll store the value. (Perhaps+[NSNumber numberWithDouble:]and-[NSNumber doubleValue]?) You’ll want to make sure you understand dictionary lookups before implementing such a strategy.