c++ - 静态 Objective-C 类中的内存

标签 c++ iphone c objective-c memoization

假设我有一个类似的类方法

+ (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
   //
}

谢谢!!

最佳答案

如果你想创建一次缓存并检查它,我通常使用 +initialize方法。此方法在第一条消息发送到类之前被调用,因此缓存将在 +function::(顺便说一下,这是一个糟糕的选择器名称)被调用之前创建。在这种情况下,我通常在 .m 文件中声明缓存变量,但在方法定义中声明它也可能有效。


编辑:应 OP 的要求添加示例:

// MyClass.m

static NSMutableDictionary* cache;

+ (void) initialize {
    cache = [[NSMutableDictionary alloc] init];
}

+ (double) cachedValueForParam1:(id)param1 param2:(id)param2 {
    // Test if (param1,param2) is in cache and return cached value.
}

显然,如果某个值不存在于缓存中,您应该有一些代码来添加该值。此外,我不知道您打算如何将 param1param2 组合为缓存的键,或者您将如何存储该值。 (也许 +[NSNumber numberWithDouble:]-[NSNumber doubleValue]?)在实现这样的策略之前,您需要确保了解字典查找。

关于c++ - 静态 Objective-C 类中的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2045735/

相关文章:

c++ - 在 gcc 中禁用 "if(0)"消除

c++ - 优化 volatile 堆栈变量的存储/构造是否合法?

ios - 共享扩展帖子照片 : Failed to determine whether URL is managed by a file provider

iphone - 如何构建 OpenSSL 并优化它的可执行文件大小?

c - Strncpy(字符串C编程)第二次表现不佳

c++ - 将 shared_ptr 的嵌套智能指针重置为 shared_ptr(或 unique_ptr),看似矛盾

c++ - 指针在 Visual Studio 2013 中被视为不可修改的左值

iphone - iPhone 应用程序可以 root 身份运行吗?

c - 编译 Clewn 时出现错误

c - 它是链表实现吗?