Objective-C编程中语句和变量的一些编写规范建议

2020-01-15 13:43:39王旭

       }
    case 3:
        // ...
        break;
    default: 
        // ...
        break;
}
枚举类型

 

使用NS_ENUM()这个宏来定义枚举,它有更强大的的类型检查和代码补全。

复制代码
typedef NS_ENUM(NSUInteger, ZOCMachineState) {
    ZOCMachineStateNone,
    ZOCMachineStateIdle,
    ZOCMachineStateRunning,
    ZOCMachineStatePaused
};

 

变量
尽量使用长的、描述性的方法和变量名。

复制代码
// 推荐
UIButton *settingsButton;

 

// 不推荐
UIButton *setBut;


常量应该以驼峰法命名,并以相关类名作为前缀。
复制代码
// 推荐
static const NSTimeInterval ZOCSignInViewControllerFadeOutAnimationDuration = 0.4;

 

// 不推荐
static const NSTimeInterval fadeOutTime = 0.4;


推荐使用常量来代替字符串字面值和数字。可以方便复用,快速修改。

 

常量应该用static声明为静态常量,而不要用#define,除非它明确作为宏来使用。

复制代码
// 推荐
static NSString * const ZOCCacheControllerDidClearCacheNotification = @"ZOCCacheControllerDidClearCacheNotification";

 

static const CGFloat ZOCImageThumbnailHeight = 50.0f;

// 不推荐
#define CompanyName @"Apple Inc."
#define magicNumber 42


常量如果需要暴露给外部,那么要在头文件中以这样的形式:
复制代码
extern NSString *const ZOCCacheControllerDidClearCacheNotification;
并在实现文件中为它赋值。

 

只有公有的常量才需要添加命名空间作为前缀。尽管实现文件中私有常量的命名可以遵循另外一种模式,你仍旧可以遵循这个规则。