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

之前,在在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];

from:http://marshal.easymorse.com/archives/4149

是指可用于全局的常量。如果只是在文件内部使用,不希望之外的地方能访问到,就需要:

 #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);
    }

猜你喜欢

转载自justsee.iteye.com/blog/1630954