问题描述
我将一些应用程序设置存储在NSUserDefaults中. NSStrings用作键.问题是我需要使用这些NSString键在整个应用程序中访问这些设置.在应用程序的某些部分访问时,我可能会打错此类字符串键.
I store some app settings in NSUserDefaults. NSStrings are used as keys. The problem is I need to access these settings throughout the app using those NSString keys. There is a chance that I mistype such string key when accessing in some part of the app.
在整个应用程序中,我都有这样的声明
Throughout the app, I have such statements
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"ReminderSwitch"];
BOOL shouldRemind = [[NSUserDefaults standardUserDefaults] boolForKey:@"ReminderSwitch"];
如何以及在哪里可以声明可以在整个应用程序中访问的全局NSString常量.这样,我就可以使用该常量,而不必担心会弄乱那些字符串键了.
How and where can I declare a global NSString constant which I can access throughout the app. I will then be able to use that constant without worrying about mistyping those string keys.
推荐答案
首先,您应该使用真正的extern C符号-而不是宏.这样做是这样的:
First, you should go for a real extern C symbol -- not a macro. this is done like so:
SomeFile.h
SomeFile.h
extern NSString *const MONConstantString;
SomeFile.m
SomeFile.m
NSString *const MONConstantString = @"MONConstantString";
请注意,如果混合使用ObjC和ObjC ++,则需要为C ++ TU指定extern "C"
,这就是为什么您会看到#define
d导出随语言而变化的原因.
note that if you use a mix of ObjC and ObjC++, you will need to specify extern "C"
for C++ TUs -- that's why you will see a #define
d export which varies by language.
然后,您需要将常量放在与其相关的接口附近.以您的示例为线索,您可能需要针对应用程序首选项的一组接口或声明.在这种情况下,您可以将声明添加到MONAppsPreferences
标头中:
Then, you will want to put the constant near the interfaces it relates to. Taking your example as a lead, you might want a set of interfaces or declarations for your app's preferences. In that case, you might add the declaration to MONAppsPreferences
header:
MONAppsPreferences.h
MONAppsPreferences.h
extern NSString *const MONApps_Pref_ReminderSwitch;
MONAppsPreferences.m
MONAppsPreferences.m
NSString *const MONApps_Pref_ReminderSwitch = @"MONApps_Pref_ReminderSwitch";
使用中:
In use:
#import "MONAppsPreferences.h"
...
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:MONApps_Pref_ReminderSwitch];
这篇关于如何声明和使用NSString全局常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!