Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

objective-c - Objective-C中的常量(Constants in Objective-C)

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

(我正在开发一个Cocoa应用程序,并且我使用常量NSString作为存储我的首选项的键名的方法。)

I understand this is a good idea, because it allows easy changing of keys if necessary.

(我知道这是一个好主意,因为它可以在必要时轻松更改密钥。)

Plus, it's the whole 'separate your data from your logic' notion.

(此外,它是整个'将您的数据与逻辑分离'的概念。)

Anyway, is there a good way to make these constants defined once for the whole application?

(无论如何,是否有一种很好的方法可以为整个应用程序定义一次这些常量?)

I'm sure that there's an easy and intelligent way, but right now my classes just redefine the ones they use.

(我确信这是一种简单而聪明的方式,但是现在我的课程只是重新定义了他们使用的课程。)

  ask by Allyn translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

((如果您的代码不会在混合C / C ++环境或其他平台上使用,则可以使用extern而不是FOUNDATION_EXPORT ))

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

(您可以在.m文件中定义这些常量)

// 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.

(应将Constants.m添加到应用程序/框架的目标中,以便将其链接到最终产品。)

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).

(使用的优点字符串常量代替#define倒是常数是可以测试用于使用指针比较平等( stringInstance == MyFirstConstant )比字符串比较快得多( [stringInstance isEqualToString:MyFirstConstant]和更容易阅读, IMO)。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...