我使用类似下面的东西。与@Quinn Taylor发布的版本不同,此版本具有以下属性:
- 创建
NSAutoreleasePool
以确保存在池。在处理诸如代码的“启动”时最好假设最差。如果游泳池已经存在,则无害。
- 创建
cache
恰好一次:
- 安全地调用
+initialize
多次(通过子类可能发生)。
- 多线程安全。不管有多少线程同时在同一时间呼叫
+initialize
,cache
保证只能创建一次。 '赢得'原子CAS的线程保留cache
,这是'松'autorelease
他们的尝试的线程。
如果你想成为非常保守,你可以添加断言检查这两个pool
和initCache
不NULL
。另外请注意,这不会确保cache
一旦创建就以多线程安全的方式使用。
#include <libkern/OSAtomic.h>
static NSMutableDictionary *cache;
+ (void)initialize
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableDictionary *initCache = [[[NSMutableDictionary alloc] init] autorelease];
_Bool didSwap = false;
while((cache == NULL) && ((didSwap = OSAtomicCompareAndSwapPtrBarrier(NULL, initCache, (void * volatile)&cache)) == false)) { /* Allows for spurious CAS failures. */ }
if(didSwap == true) { [cache retain]; }
[pool release];
pool = NULL;
}
复制http://stackoverflow.com/questions/554969/using-static-keyword-in-objective-c-when-defining-a-cached-variable – joshperry 2010-01-12 01:19:37