简体   繁体   English

相当于Java ThreadLocal变量的Objective C / Swift

[英]Equivalent on Objective C/Swift of Java ThreadLocal Variables

In Java, we have the ThreadLocal class: 在Java中,我们有ThreadLocal类:

This class provides thread-local variables. 该类提供线程局部变量。 These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. 这些变量与它们的正常对应物的不同之处在于,访问一个变量的每个线程(通过其getset方法)都有自己独立初始化的变量副本。 ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (eg, a user ID or Transaction ID). ThreadLocal实例通常是希望将状态与线程(例如,用户ID或事务ID)相关联的类中的private static字段。

Example: 例:

private static final ThreadLocal<StringBuilderHelper>
    threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() {
        @Override
        protected StringBuilderHelper initialValue() {
            return new StringBuilderHelper();
        }
    };

Is there any equivalent in Objective C or Swift to simulate this behavior? 在Objective C或Swift中是否有任何等价物来模拟这种行为? Can i just use on Swift: 我可以在Swift上使用:

static let String = someInitialValue()

and achieve the same goal? 并实现同样的目标?

Have a look at NSThread threadDictionary . 看看NSThread threadDictionary I believe this is roughly the same thing. 我相信这大致是一回事。

A typical use in Objective-C might be: Objective-C中的典型用法可能是:

NSMutableDictionary *threadData = [[NSThread currentThread] threadDictionary];
threadData[someKey] = someObject; // write

someObject = threadData[someKey]; // read

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM