2012-08-13 22 views
11

可能重複:
Constants in Objective C如何聲明和使用NSString全局常量

我在存儲NSUserDefaults的一些應用程序設置。 NSStrings被用作鍵。問題是我需要使用這些NSString鍵在整個應用程序中訪問這些設置。在應用程序的某些部分訪問時,我有可能輸錯這種字符串鍵。

整個應用程序,我有這樣的語句

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"ReminderSwitch"]; 

BOOL shouldRemind = [[NSUserDefaults standardUserDefaults] boolForKey:@"ReminderSwitch"]; 

如何以及在哪裏可以聲明一個全局的NSString常數,我可以在整個應用程序進行訪問。然後,我將能夠使用這個常量而不用擔心忘記這些字符串鍵。

回答

5

你似乎在尋找的只是一種在你的應用中定義字符串常量的方法。

this questionthis answer它,我已經引述如下:

您應該創建像

// Constants.h 
FOUNDATION_EXPORT NSString *const MyFirstConstant; 
FOUNDATION_EXPORT NSString *const MySecondConstant; 
//etc. 

一個頭文件可以包含在使用的每個文件這個文件常量或在項目的預編譯頭文件中。

您定義的.m文件,這些常量像

// Constants.m 
NSString *const MyFirstConstant = @"FirstConstant"; 
NSString *const MySecondConstant = @"SecondConstant"; 

Constants.m使得它在最終產品鏈接應該添加到您的應用程序/框架的目標。

使用代替#define'd常量 字符串常量的好處是,你可以使用指針比較 (stringInstance == MyFirstConstant)比字符串 比較([stringInstance isEqualToString:MyFirstConstant])(和 更易於閱讀,IMO)快得多測試相等。

與感謝巴里·沃克:)

+0

他只需要應用程序中的常量(內部li nkage)所以我想知道你爲什麼建議他出口它們(外部鏈接)? – malhal 2016-07-31 22:36:07

9

。你的想法是對的,我想。例如,我提出Const.h /米文件象下面這樣:

Const.h

extern NSString *const UserIdPrefKey; 
extern NSString *const PasswordPrefKey; 
extern NSString *const HomepagePrefKey; 

Const.m

#import "AEConst.h" 

NSString *const UserIdPrefKey = @"UserIdPrefKey"; 
NSString *const PasswordPrefKey = @"PasswordPrefKey"; 
NSString *const HomepagePrefKey = @"UrlHomepagePrefKey"; 

只有Const.h必須導入。

當您編寫代碼時,Xcode支持編寫密鑰名稱,以便避免錯過輸入。

5

最簡單的方法是製作簡單的.h文件,像Utils。H和寫有如下代碼:

#define kUserDefaults @"ReminderSwitch"

+3

是啊,不太安全,有一個其他目標c文件覆蓋的機會,而沒有得到注意:( – thndrkiss 2015-02-25 23:16:10

13

首先,你應該去一個真正的外部C符號 - 不是宏。這是像這樣做:

SomeFile.h

extern NSString *const MONConstantString; 

SomeFile.m

NSString *const MONConstantString = @"MONConstantString"; 

請注意,如果您使用ObjC和ObjC++的混合,則需要對C指定extern "C" ++ TU - 這就是爲什麼你會看到一個#define D導出,因語言而異。


然後,你會想把常量放在它所涉及的接口附近。以你的榜樣爲榜樣,你可能需要一組接口或聲明來表示你的應用的偏好。在這種情況下,你可能會在聲明添加到MONAppsPreferences頭:

MONAppsPreferences.h

extern NSString *const MONApps_Pref_ReminderSwitch; 

MONAppsPreferences.m

NSString *const MONApps_Pref_ReminderSwitch = @"MONApps_Pref_ReminderSwitch"; 

在使用中:

#import "MONAppsPreferences.h" 
... 
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:MONApps_Pref_ReminderSwitch];