Objective-C 中的常量 [英] Constants in Objective-C

查看:32
本文介绍了Objective-C 中的常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Cocoa 应用程序,我正在使用常量NSStrings 作为存储我偏好的键名的方式.

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

推荐答案

你应该创建一个像

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

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

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

你在一个 .m 文件中定义这些常量

You define these constants in a .m file like

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

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

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

使用字符串常量而不是 #define'd 常量的优点是您可以使用指针比较 (stringInstance == MyFirstConstant) 来测试相等性,这要快得多比字符串比较 ([stringInstance isEqualToString:MyF​​irstConstant])(更容易阅读,IMO).

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

这篇关于Objective-C 中的常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆