使用threadDictionary这个代码线程是否安全?

时间:2013-07-31 20:15:09

标签: iphone ios objective-c

+(NSString*)FromNumber:(NSNumber*)number
{
    NSString *key = akey;
    NSNumberFormatter *numberFormatter = [[[NSThread currentThread] threadDictionary] objectForKey:key];
    if(!numberFormatter)
    {
        numberFormatter = [self getDecimalNumberFormatterWithDigits:2];
        [numberFormatter setFormatterBehavior:NSNumberFormatterPercentStyle];

        [numberFormatter setNegativeSuffix:@"%"];
        [numberFormatter setPositiveSuffix:@"%"];
        [numberFormatter setNilSymbol:@""];
        [numberFormatter setLocale:[ISMDateUtilities enUSPosixLocale]];

        [[[NSThread currentThread] threadDictionary] setValue:numberFormatter forKey:key];
    }
    return [numberFormatter stringForObjectValue:number];
}

我很好奇的是使用threadDictionary同步一段代码?

谢谢!

1 个答案:

答案 0 :(得分:4)

此代码的线程安全性取决于akey是常量。如果是,那么是的,这个方法是线程安全的,因为它不共享线程之间的任何状态。 (我不确定你的意思是“同步”,但据我所知,这里没有同步工作。)