在objc项目中使用常量的最佳实践

 

之前,在在objc项目中使用常量中,使用c的预处理#define来设置常量。比如,可以做个头文件,然后在需要的类文件中import,使用常量。

但这不是最佳实践。这样做可能是最好的方式,首先在比如叫Constants.h的头文件中:

#import

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];

相关文章:

  • 2021-11-03
  • 2021-09-27
  • 2021-05-24
  • 2022-12-23
  • 2022-01-24
  • 2022-12-23
  • 2022-12-23
  • 2021-05-28
猜你喜欢
  • 2021-05-20
  • 2022-12-23
  • 2022-03-10
  • 2021-10-24
  • 2021-10-07
  • 2021-07-11
  • 2022-12-23
相关资源
相似解决方案