等效于Java ThreadLocal变量的Objective C / Swift [英] Equivalent on Objective C/Swift of Java ThreadLocal Variables

查看:169
本文介绍了等效于Java ThreadLocal变量的Objective C / Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我们有 ThreadLocal 类:

In Java, we have the ThreadLocal class:


此类提供线程局部变量。这些变量与普通对象的不同之处在于,访问其中的每个线程(通过其 get set 方法)都有自己的,独立初始化的变量副本。 ThreadLocal 实例通常是希望将状态与线程关联的类中的私有静态字段(例如,用户ID或交易ID)。

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. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

示例:

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

在Objective C或Swift中是否有任何等效模拟这种行为?我可以在Swift上使用:

Is there any equivalent in Objective C or Swift to simulate this behavior? Can i just use on Swift:

static let String = someInitialValue()

并实现相同的目标?

推荐答案

查看 NSThread threadDictionary 。我认为这大致相同。

Have a look at NSThread threadDictionary. I believe this is roughly the same thing.

Objective-C中的典型用法可能是:

A typical use in Objective-C might be:

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

someObject = threadData[someKey]; // read

这篇关于等效于Java ThreadLocal变量的Objective C / Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆