bug^君 2009-02-11 21:52 采纳率: 25%
浏览 355
已采纳

Objective-c 中的常数

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.

转载于:https://stackoverflow.com/questions/538996/constants-in-objective-c

  • 写回答

13条回答 默认 最新

  • 斗士狗 2009-02-11 22:38
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(12条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站