【问题标题】:Global variables in my Constants file我的常量文件中的全局变量
【发布时间】:2013-12-25 14:02:52
【问题描述】:

到目前为止,如果我需要访问我刚刚添加的应用程序中的全局变量

#define PATH [NSString stringWithFormat:@"www.url.com"]

到我的Constants.h 文件。

我需要从我的服务器获取PATH 值。 如何将我从服务器获取的值分配给像上面这样的宏 \string 并且仍然能够在我的应用程序的任何地方只使用变量 PATH? (不用像属性一样命名类,如class.PATH

这行得通:

#import <Foundation/Foundation.h>

NSString* PATH;

@interface Constants : NSObject
+(void)getPathFromServer;

@end  

PATH 可以从我的应用程序的任何位置访问,但我不确定这是否应该是要走的路。

【问题讨论】:

  • 为什么不像#define PTAH @"www.url.com"那样直接定义宏。
  • @johnMa 未来有可能会发生变化,我想保持动态,而不只是为 url 更新应用程序。

标签: ios objective-c macros global


【解决方案1】:

据我所知,您需要定义一个动态更改其 url 内容的宏。 如果我是对的,您可能需要一个带有变量的Vararg Macros

#define PATH(...) [NSString stringWithFormat:@"%@",__VA_ARGS__]

【讨论】:

  • 嗯,我只需要为每个应用午餐设置一次 PATH,而不是每次调用它。
【解决方案2】:

您可以使用外部关键字 示例:

//Header file
extern NSString * const path;

// .m file under implementation
NSString * const Ppath = [NSString stringWithFormat:@"www.url.com"];

看看这些
Constants in Objective C
#define vs const in Objective-C

【讨论】:

  • 我需要在编译时设置,比如我上面提到的m文件中的getPathFromServer方法下。试图将NSString * const Ppath = [NSString stringWithFormat:@"www.url.com"]; 放在一个方法中给了我一个链接错误。 (甚至可以在方法中设置 const 吗?)
猜你喜欢
  • 2016-02-03
  • 1970-01-01
  • 2014-12-02
  • 2011-12-27
  • 2010-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多