Objective-c 中的常量
我想为我的应用程序添加一些常量键,这些常量可以在程序中的任何位置访问。因此,我在接口文件中声明常量:
#import <UIKit/UIKit.h>
NSString * MIN_INTERVAL_KEY = @"MIN_INTERVAL_KEY";
NSString * MAX_TOBACCO_KEY = @"MAX_TOBACCO_KEY";
NSString * ICON_BADGE = @"ICON_BADGE";
@interface SmokingViewController : UIViewController {
}
我想从 MinIntervalViewController 类访问它们:
- (void)viewDidAppear:(BOOL)animated {
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
if (user) {
self.selectedValue = [user objectForKey:MIN_INTERVAL_KEY];
}
[super viewDidAppear:animated];
}
但应用程序在 MinIntervalViewController 类中显示错误:
错误:'MIN_INTERVAL_KEY' 未声明(首次在此函数中使用)
我错过了什么吗?任何帮助将不胜感激。
谢谢
I would like to add some constant keys for my application, these constants can be accessed anywhere in program. So I declare the constants in interface file:
#import <UIKit/UIKit.h>
NSString * MIN_INTERVAL_KEY = @"MIN_INTERVAL_KEY";
NSString * MAX_TOBACCO_KEY = @"MAX_TOBACCO_KEY";
NSString * ICON_BADGE = @"ICON_BADGE";
@interface SmokingViewController : UIViewController {
}
And I would like to access them from the MinIntervalViewController class:
- (void)viewDidAppear:(BOOL)animated {
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
if (user) {
self.selectedValue = [user objectForKey:MIN_INTERVAL_KEY];
}
[super viewDidAppear:animated];
}
But the application shows an error in the MinIntervalViewController class:
error: 'MIN_INTERVAL_KEY' undeclared (first use in this function)
Do I miss something? Any help would be appreciated.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Constants.h
Constants.m
使用方法:
然后,只需调用您要使用的特定变量即可。
Constants.h
Constants.m
To use:
Then, simply call the specific variable you wish to use.
在 .h 文件中:
在一个 (!) .m 文件中:
您似乎错过了实际上
导入
声明 MIN_INTERVAL_KEY 的头文件;-) 因此,如果您在中声明它SmokingViewController.h
但想在MinIntervalViewController.m
中使用它,那么您需要在MinIntervalViewController.m
中导入“SmokingViewController.h”
/代码>。由于 Objective-C 实际上或多或少是对 C 的扩展,所以所有 C 可见性规则都适用。另外,有助于调试此类内容的方法是右键单击 Xcode 中的 .m 文件并选择“预处理”。然后您会看到文件预处理,即 CPP 完成其工作之后。这就是 C 编译器真正正在消化的内容。
In the .h file:
In one (!) .m file:
And what you seemed to have missed is to actually
import
the header file declaring MIN_INTERVAL_KEY ;-) So if you declared it inSmokingViewController.h
but like to use it inMinIntervalViewController.m
, then you need toimport "SmokingViewController.h"
in yourMinIntervalViewController.m
. Since Objective-C is really more or less an extension to C all C visibility rules apply.Also, what helps to debug things like that is to right-click on the .m file in Xcode and select "Preprocess". Then you see the file preprocess, i.e. after CPP has done its work. This is what the C compiler REALLY is digesting.