等效于Java ThreadLocal变量的Objective C / Swift
在Java中,我们有ThreadLocal
类:
该类提供线程局部变量。 这些变量与它们的正常对应物的不同之处在于,访问一个变量的每个线程(通过其
get
或set
方法)都有自己独立初始化的变量副本。ThreadLocal
实例通常是希望将状态与线程相关联的类中的private static
字段(例如,用户ID或事务ID)。
例:
private static final ThreadLocal threadLocalStringBuilderHelper = new ThreadLocal() { @Override protected StringBuilderHelper initialValue() { return new StringBuilderHelper(); } };
Objective C或Swift中是否有任何等效模拟这种行为? 我可以在Swift上使用:
static let String = someInitialValue()
并实现同样的目标?
看看NSThread threadDictionary
。 我相信这大致是一回事。
Objective-C中的典型用法可能是:
NSMutableDictionary *threadData = [[NSThread currentThread] threadDictionary]; threadData[someKey] = someObject; // write someObject = threadData[someKey]; // read