0%

《编写高质量iOS与OS X代码的52个有效方法》阅读笔记

《编写高质量iOS与OS X代码的52个有效方法》


第4条:多用类型常量,少用#define预处理指令

  • 不要用预处理指令定义常量。这样定义出来的常量不含类型信息,编译器只是在编译前做替换操作。即使有人重新定义,编译器也不会产生警告。

  • 在实现文件中使用static const来定义只在编译单元内可见的常量。由于此常量不在全局符号表中,所以无须为其名称加前缀。

    1
    2
    3
    4
    5
    // 尽量少使用
    // #define ANIMATION_DURATION 0.3

    // 常量局限于implementation file之内,则在变量名前面加字母k
    static const NSTimeInterval kAnimationDuration = 0.3;
  • 在头文件中使用extern const来声明全局常量,并在相应实现文件中定义其值。这种常量要出现在全局符号表中,所以其名称应加一区隔,通常用与之相关的类名做前缀。

    1
    2
    3
    4
    5
    6
    7
    // EOCAnimatedView.h
    extern const NSTimeInterval EOCAnimatedViewAnimationDuration;
    extern NSString * const EOCLoginManagerDidLoginNotification;

    // EOCAnimatedView.m
    const NSTimeInterval EOCAnimatedViewAnimationDuration = 0.3;
    NSString * const EOCLoginManagerDidLoginNotification = @"EOCLoginManagerDidLoginNotification";