之前,在在objc项目中使用常量中,使用c的预处理#define来设置常量。比如,可以做个头文件,然后在需要的类文件中import,使用常量。
但这不是最佳实践。这样做可能是最好的方式,首先在比如叫Constants.h的头文件中:
#import <Foundation/Foundation.h>
extern NSString * const kInitURL;
@interface Constants : NSObject {
}
@end
这里使用到extern c关键字,表示这个变量已经声明,只是引用。const关键字表示变量是常量,不可修改。
在objc的约定里,常量也是大小写混排的驼峰命名规则,首字母小写,另外,第一个字母是k。
然后,在Constants.m文件中:
#import "Constants.h"
NSString * const kInitURL = @"http://marshal.easymorse.com";
@implementation Constants
@end
在这里给常量kInitURL赋值。
如何使用常量?只需在所需的m文件引入Constants头文件,下面是使用示例:
#import "BasicDemosViewController.h"
#import "Constants.h"@implementation BasicDemosViewController
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
NSLog(@"load view: %@",kInitURL);
}
使用这种方式,比通过宏预定义的优点是,可以对常量进行指针比较操作,这是#define做不到的。即:
[myURL isEqualToString:kInitURL];
上文的常量,是指可用于全局的常量。如果只是在文件内部使用,不希望之外的地方能访问到,就需要:
#import "BasicDemosViewController.h"
#import "Constants.h"NSString * const kMyURL=@"http://marshal.easymorse.com";
@implementation BasicDemosViewController
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
NSLog(@"load view: %@, %@",kInitURL,kMyURL);
}
另附:在objc项目中使用常量
objc不像java,有静态常量。比如:
public static final RADIAS=180;
目前我的做法是,使用c的预处理#define。比如,在头文件中:
#define MIN_VELOCITY 10
#define LOOP_COUNT 100@interface AnimationView : UIView <UIGestureRecognizerDelegate>{
在代码中使用:
if (data.panLocation.x<MIN_X) {
data.panLocation.x=MIN_X;
}这些预定义常量,会在编译器编译的时候用define中定义的字符串替代。
书中说在标准C中const定义的变量是外连接的,即如果一个编译单元中定义了一个全局const常量,则其在其他编译单元中是可见的,如果其他编译单元也定义了同名const常量就会产生重复定义错误。这一点与C++不同,C++中const定义的变量是内连接的,即每个编译单元定义的全局const常量是自己独有的。
Objective-C是标准C的另一种扩展,那么我犯的错误也就很明显了——当多个编译单元都引用那个define.h文件时出现了重复定义错。
今天来到机房一试,果然如此,只要将
const int NUMOFGHOST = 4;
改为
static const int NUMOFGHOST = 4;
就顺利编译通过了。这里的static是用来把定义的const常量标记为对外不可见的。
这里顺便抱怨一句:这xcode也太不人性化了,重复定义就说重复定义嘛,非要用红红的字标出来"Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 failed with exit code 1",反倒是很重要的那句"ld: duplicate symbol _NUMOFGHOST in /Users/asfgasiyf/Desktop/pacMan/build/pacMan.build/Debug-iphonesimulator/pacMan.build/Objects-normal/i386/MazeView.o and /Users/asfgasiyf/Desktop/pacMan/build/pacMan.build/Debug-iphonesimulator/pacMan.build/Objects-normal/i386/pacManAppDelegate.o"用灰灰的颜色显示,也不懂得突出一下重点??
联系客服