我想让自己的事情变得更轻松,因此我正在创建一个字典,该字典供其他功能使用(按对象或按对象访问键),但是该字典始终是静态的。是这样做的好方法,还是我需要财产或其他东西?
+ (NSDictionary *)dictionaryWithCategoriesAndStrings
{
return @{
kNewsCategoryAll : @(NewsCategoryAll),
kNewsCategoryRadio : @(NewsCategoryRadio),
kNewsCategoryEconomics : @(NewsCategoryEconomics),
kNewsCategoryCulture : @(NewsCategoryCulture),
kNewsCategorySport : @(NewsCategorySport),
kNewsCategoryTravel : @(NewsCategoryTravel),
kNewsCategoryMusic : @(NewsCategoryMusic),
kNewsCategorySociety : @(NewsCategorySociety),
kNewsCategoryHealth : @(NewsCategoryHealth)
};
}
因此,现在我总是通过函数[self dictionaryWithCategoriesAndString]访问同一词典。
注意:这些键是在顶部声明的静态字符串,而对象是带有整数的NSNumbers。
最佳答案
您可以在方法中创建它,而不用将其暴露给整个类,而仅使用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/