gpt4 book ai didi

ios - 不会改变的 NSDictionary

转载 作者:行者123 更新时间:2023-11-28 18:33:15 24 4
gpt4 key购买 nike

我想让自己的事情变得更容易,所以我正在创建一个字典,供其他函数使用(按对象或按键访问对象),但该字典始终是静态的。这是做这件事的好方法还是我需要属性(property)或其他东西?

+ (NSDictionary *)dictionaryWithCategoriesAndStrings
{
return @{
kNewsCategoryAll : @(NewsCategoryAll),
kNewsCategoryRadio : @(NewsCategoryRadio),
kNewsCategoryEconomics : @(NewsCategoryEconomics),
kNewsCategoryCulture : @(NewsCategoryCulture),
kNewsCategorySport : @(NewsCategorySport),
kNewsCategoryTravel : @(NewsCategoryTravel),
kNewsCategoryMusic : @(NewsCategoryMusic),
kNewsCategorySociety : @(NewsCategorySociety),
kNewsCategoryHealth : @(NewsCategoryHealth)
};
}

所以现在我总是通过函数 [self dictionaryWithCategoriesAndString] 访问同一个字典;

注意:这些键是在顶部声明的静态字符串,对象是带整数的 NSNumber。

最佳答案

与其将静态暴露给整个类,不如在方法中创建它,并使用 gcd 仅初始化一次:

线程安全的。

+ (NSDictionary *)dictionaryWithCategoriesAndStrings {
static NSDictionary *dict;

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dict = @{
kNewsCategoryAll : @(NewsCategoryAll),
kNewsCategoryRadio : @(NewsCategoryRadio),
kNewsCategoryEconomics : @(NewsCategoryEconomics),
kNewsCategoryCulture : @(NewsCategoryCulture),
kNewsCategorySport : @(NewsCategorySport),
kNewsCategoryTravel : @(NewsCategoryTravel),
kNewsCategoryMusic : @(NewsCategoryMusic),
kNewsCategorySociety : @(NewsCategorySociety),
kNewsCategoryHealth : @(NewsCategoryHealth)
};
});

return dict;
}

关于ios - 不会改变的 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23890898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com