类常量 [英] Class Constants

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

问题描述

我有几个obj-c类,每个类都需要在switch语句中使用的一些常量。

I have several obj-c classes, each of which require a number of constants that are used in switch statements.

我曾尝试在这些中定义这些数值常量.m文件使用 #define 预处理程序指令。所有这些常数都以'kCell'开头。这似乎运作良好,但无论我在项目中的哪个位置,Xcode的代码意义都会向我呈现每个'kCell'前缀常量。 #define 常量是否具有全局范围?如果是这样,定义纯本地类常量的最佳方法是什么,这些常量不会在其他类中使用类似命名的常量进行分类?

I had tried defining these numerical constants in the .m file using the #define preprocessor instruction. All these constants begin with 'kCell'. This seems to work well but Xcode's code sense is presenting me with every 'kCell' prefixed constant no matter where I am in the project. Do #define constants have global scope? If so, what is the best way to define purely local class constants that won't class with similarly named constants in other classes?

推荐答案

拥有自己的常量文件,如MyConstants。

Have your own constant file like MyConstants.

在MyConstants.h中声明所有常量:

In MyConstants.h declare all your constants:

static const int kRedisplayTileCount = 5 ;
extern  NSString* const kCellTitleKey;

在MyConstants.m中定义它们

and in MyConstants.m define them

NSString* const kCellTitleKey = @"CellTitle";

通过将常量保存在单独的文件中,您可以轻松跟踪它们并更改其值。

By keeping constants in separate file, it will be easy for you to trace them and change their value.

这是定义纯常量的最佳方法。这也可以避免重复键。

This is the best way to define purely constants. And this will avoid duplicate keys also.

只有你需要做的是在你的其他类中导入这个类:

Only you need to do is import this class in you other classes:

#import "MyConstants.h"

并使用这些密码:

obj = [[NSUserDefaults standardUserDefaults] integerForKey: kCellTitleKey];

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

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