Constants in Objective-C

后端 未结 14 1289
广开言路
广开言路 2020-11-21 22:10

I\'m developing a Cocoa application, and I\'m using constant NSStrings as ways to store key names for my preferences.

I understand this is a good idea b

14条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 22:42

    You should create a header file like

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

    (you can use extern instead of FOUNDATION_EXPORT if your code will not be used in mixed C/C++ environments or on other platforms)

    You can include this file in each file that uses the constants or in the pre-compiled header for the project.

    You define these constants in a .m file like

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

    Constants.m should be added to your application/framework's target so that it is linked in to the final product.

    The advantage of using string constants instead of #define'd constants is that you can test for equality using pointer comparison (stringInstance == MyFirstConstant) which is much faster than string comparison ([stringInstance isEqualToString:MyFirstConstant]) (and easier to read, IMO).

提交回复
热议问题