Objective-C 编码规范(中文)

作者: LovelyYilia | 来源:发表于2016-06-30 23:16 被阅读176次

    注:以下皆为翻译,如有错误或疏漏,请指正。谢谢☺

    简介

    本代码规范旨在保持raywenderlich的书刊、教程、sdk统一。

    荣誉

    ......

    背景

    如果本文中规范有遗漏,可以从参考以下Apple 推荐的编码规范。

    目录

    <a name="language"></a>语言

    用美式英语.

    推荐:

    UIColor *myColor = [UIColor whiteColor];
    

    不推荐:

    UIColor *myColour = [UIColor whiteColor];
    

    <a name="code-organization"></a>代码组织

    #pragma mark - 分类方法、函数 、protocol、delegate 等.

    #pragma mark - Lifecycle
    
    - (instancetype)init {}
    - (void)dealloc {}
    - (void)viewDidLoad {}
    - (void)viewWillAppear:(BOOL)animated {}
    - (void)didReceiveMemoryWarning {}
    
    #pragma mark - Custom Accessors
    
    - (void)setCustomProperty:(id)value {}
    - (id)customProperty {}
    
    #pragma mark - IBActions
    
    - (IBAction)submitData:(id)sender {}
    
    #pragma mark - Public
    
    - (void)publicMethod {}
    
    #pragma mark - Private
    
    - (void)privateMethod {}
    
    #pragma mark - Protocol conformance
    #pragma mark - UITextFieldDelegate
    #pragma mark - UITableViewDataSource
    #pragma mark - UITableViewDelegate
    
    #pragma mark - NSCopying
    
    - (id)copyWithZone:(NSZone *)zone {}
    
    #pragma mark - NSObject
    
    - (NSString *)description {}
    

    <a name="spacing"></a>空格

    • 用2个或4个空格缩进. 不要用 Tab 缩进. 在Xcode的preference设置。
    • 方法(及 (if/else/switch/while etc.) 开始在行末,结束在新的一行中。

    推荐:

    if (user.isHappy) {
      //Do something
    } else {
      //Do something else
    }
    

    不推荐:

    if (user.isHappy)
    {
        //Do something
    }
    else {
        //Do something else
    }
    
    • 方法间保留一行空.
    • 用自动同步。但是如果必要, @synthesize@dynamic 被分别声明在不同行。
    • 避免冒号对其的写法. 某些情景下,冒号数量会超过2个,按照冒号对其会更有可读性. 请 不要在包含 block 的方法中按照冒号对其,因为 xcode 会认为这不合法.

    推荐:

    // blocks are easily readable
    [UIView animateWithDuration:1.0 animations:^{
      // something
    } completion:^(BOOL finished) {
      // something
    }];
    

    不推荐:

    // colon-aligning makes the block indentation hard to read
    [UIView animateWithDuration:1.0
                     animations:^{
                         // something
                     }
                     completion:^(BOOL finished) {
                         // something
                     }];
    

    <a name="comments"></a>注释

    有必要的话,添加注释解释为什么。 注释掉的代码应该被删除。

    避免块注释,代码应该具有自我描述性。 特殊: 这不适用于文档生成器。

    <a name="naming"></a>命名

    Apple 命名规范应该一直被遵守,详见内存管理规则 (NARC)。

    长的具有描述性的名称是好的。

    推荐:

    UIButton *settingsButton;
    

    不推荐:

    UIButton *setBut;
    

    3个字母的前缀用在类名和常量中, Core Data 中的entity names不需要前缀。
    前缀所有字母大写。

    推荐:

    static NSTimeInterval const RWTTutorialViewControllerNavigationFadeAnimationDuration = 0.3;
    

    不推荐:

    static NSTimeInterval const fadetime = 1.7;
    

    小写字母开始驼峰命名。用自动同步而不是 @synthesize。

    推荐:

    @property (strong, nonatomic) NSString *descriptiveVariableName;
    

    不推荐:

    id varnm;
    

    <a name="underscores"></a>下划线

    访问属性用 self.
    局部变量不应该包含下划线。

    <a name="methods"></a>方法

    方法签名中, 空格紧接着方法类型符号(-/+)。每段用空格分开(符合 Apple编码风格)。 用关键字描述参数。

    and是被保留的, 不应该用在多参数的描述关键字中。initWithWidth:height:,示例如下:

    推荐:

    - (void)setExampleText:(NSString *)text image:(UIImage *)image;
    - (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;
    - (id)viewWithTag:(NSInteger)tag;
    - (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height;
    

    不推荐:

    -(void)setT:(NSString *)text i:(UIImage *)image;
    - (void)sendAction:(SEL)aSelector :(id)anObject :(BOOL)flag;
    - (id)taggedView:(NSInteger)tag;
    - (instancetype)initWithWidth:(CGFloat)width andHeight:(CGFloat)height;
    - (instancetype)initWith:(int)width and:(int)height;  // Never do this.
    

    <a name="variables"></a>变量

    变量命名应该具有描述性. 避免单个字如for()。*紧连着变量。 e.g., NSString *text 而不是像 NSString* textNSString * text

    私有属性 替代实例变量. 虽然实例变量是有效的。

    避免直接访问实例变量除非在方法(init, initWithCoder:, etc…), dealloc 以及 setters 和 getters. 更多信息,详见 这里

    推荐:

    @interface RWTTutorial : NSObject
    
    @property (strong, nonatomic) NSString *tutorialName;
    
    @end
    

    不推荐:

    @interface RWTTutorial : NSObject {
      NSString *tutorialName;
    }
    

    <a name="property-attributes"></a>属性

    属性列表应该被明确列出,以便初学者识别。首先是 storage然后 atomicity, 这与从 Interface Builder自动生成的 UI 属性一致。

    推荐:

    @property (weak, nonatomic) IBOutlet UIView *containerView;
    @property (strong, nonatomic) NSString *tutorialName;
    

    不推荐:

    @property (nonatomic, weak) IBOutlet UIView *containerView;
    @property (nonatomic) NSString *tutorialName;
    

    可变属性 (e.g. NSString) 应该用copy 而不是 strong
    为什么呢? 即使你明确声明为 NSString ,也会有人传NSMutableString类型并改变它。

    推荐:

    @property (copy, nonatomic) NSString *tutorialName;
    

    不推荐:

    @property (strong, nonatomic) NSString *tutorialName;
    

    <a name="dot-notation-syntax"></a>.语法

    .语法也调用了 setter getter方法 更多 信息

    .语法应该 总是 被用来取得可变属性,这也让代码更简洁. []被推荐用在其他任何情形。

    推荐:

    NSInteger arrayCount = [self.array count];
    view.backgroundColor = [UIColor orangeColor];
    [UIApplication sharedApplication].delegate;
    

    不推荐:

    NSInteger arrayCount = self.array.count;
    [view setBackgroundColor:[UIColor orangeColor]];
    UIApplication.sharedApplication.delegate;
    

    <a name="literals"></a>字面量

    NSString, NSDictionary, NSArray, and NSNumber用字面量创建不可变变量。 特别需要注意nil 不能被放在NSArrayNSDictionary 字面量中, 否则会导致闪退.

    推荐:

    NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"];
    NSDictionary *productManagers = @{@"iPhone": @"Kate", @"iPad": @"Kamal", @"Mobile Web": @"Bill"};
    NSNumber *shouldUseLiterals = @YES;
    NSNumber *buildingStreetNumber = @10018;
    

    不推荐:

    NSArray *names = [NSArray arrayWithObjects:@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul", nil];
    NSDictionary *productManagers = [NSDictionary dictionaryWithObjectsAndKeys: @"Kate", @"iPhone", @"Kamal", @"iPad", @"Bill", @"Mobile Web", nil];
    NSNumber *shouldUseLiterals = [NSNumber numberWithBool:YES];
    NSNumber *buildingStreetNumber = [NSNumber numberWithInteger:10018];
    

    <a name="constants"></a>常量

    用常量定义 string类型字面量数字
    常量应该被定义为 static 而不是 #define,除非要用作宏。

    推荐:

    static NSString * const RWTAboutViewControllerCompanyName = @"RayWenderlich.com";
    
    static CGFloat const RWTImageThumbnailHeight = 50.0;
    

    不推荐:

    #define CompanyName @"RayWenderlich.com"
    
    #define thumbnailHeight 2
    

    <a name="enumerated-types"></a>枚举类型

    枚举类型用NS_ENUM()

    示例:

    typedef NS_ENUM(NSInteger, RWTLeftMenuTopItemType) {
      RWTLeftMenuTopItemMain,
      RWTLeftMenuTopItemShows,
      RWTLeftMenuTopItemSchedule
    };
    

    也可以像这样:

    typedef NS_ENUM(NSInteger, RWTGlobalConstants) {
      RWTPinSizeMin = 1,
      RWTPinSizeMax = 5,
      RWTPinCountMin = 100,
      RWTPinCountMax = 500,
    };
    

    避免老 enum写法,除非写 CoreFoundation C。

    不推荐:

    enum GlobalConstants {
      kMaxPinSize = 5,
      kMaxPinCount = 500,
    };
    

    <a name="case-statements"></a>Case 状态

    case 中{}并非强制要求,但代码超过一行应该加上{}

    switch (condition) {
      case 1:
        // ...
        break;
      case 2: {
        // ...
        // Multi-line example using braces
        break;
      }
      case 3:
        // ...
        break;
      default: 
        // ...
        break;
    }
    
    

    多个case公用一个结果需要注释明确说明。

    switch (condition) {
      case 1:
        // ** fall-through! **
      case 2:
        // code executed for values 1 and 2
        break;
      default: 
        // ...
        break;
    }
    
    

    枚举类型不需要default。如:

    RWTLeftMenuTopItemType menuType = RWTLeftMenuTopItemMain;
    
    switch (menuType) {
      case RWTLeftMenuTopItemMain:
        // ...
        break;
      case RWTLeftMenuTopItemShows:
        // ...
        break;
      case RWTLeftMenuTopItemSchedule:
        // ...
        break;
    }
    

    <a name="private-properties"></a>私有属性

    私有属性放在实现文件的匿名扩展@interface @end中。匿名扩展可以在测试中通过<headerfile>+Private.h获取。

    示例:

    @interface RWTDetailViewController ()
    
    @property (strong, nonatomic) GADBannerView *googleAdView;
    @property (strong, nonatomic) ADBannerView *iAdView;
    @property (strong, nonatomic) UIWebView *adXWebView;
    
    @end
    

    <a name="booleans"></a>布尔值

    Objective-C 用 YESNO. 因此 truefalse 仅在 CoreFoundation, C 或 C++ 中使用. 因为 nil 代表 NO 因此没有必要将 nil 和 NO进行比较. 不要直接和 YES比较, 因为 YES 等值于1, BOOL 可以比较到8bits的值.

    推荐:

    if (someObject) {}
    if (![anotherObject boolValue]) {}
    

    不推荐:

    if (someObject == nil) {}
    if ([anotherObject boolValue] == NO) {}
    if (isAwesome == YES) {} // Never do this.
    if (isAwesome == true) {} // Never do this.
    

    一个布尔变量是形容性的话可以添加is做前缀除了传统用法,如:

    @property (assign, getter=isEditable) BOOL editable;
    

    参考Cocoa Naming Guidelines

    <a name="conditionals"></a>条件语句

    条件体必须包含在{}内。 否则请参考even more dangerous defect.

    推荐:

    if (!error) {
      return success;
    }
    

    不推荐:

    if (!error)
      return success;
    

    if (!error) return success;
    

    <a name="ternary-operator"></a>三目运算符

    三目运算符 ?: , 仅在代码简洁明了的情况下使用。一个比较条件的情况下才使用?:。多个比条件比较的情况下用 if .通常,?:的最佳使用场景是给一个变量按条件赋值。

    非 布尔值应该同谋变量进行比较,并且应该添加圆括号增加可读性。 如果被比较的为布尔值,则不需要添加圆括号。

    推荐:

    NSInteger value = 5;
    result = (value != 0) ? x : y;
    
    BOOL isHorizontal = YES;
    result = isHorizontal ? x : y;
    

    不推荐:

    result = a > b ? x = c > d ? c : d : y;
    

    <a name="init-methods"></a>Init 方法

    Init方法应该遵循Apple的模板, 返回instancetype 而不是id

    - (instancetype)init {
      self = [super init];
      if (self) {
        // ...
      }
      return self;
    }
    

    详见 类构造方法

    <a name="class-constructor-methods"></a>类构造方法

    类构造方法应该返回 instancetype 而不是id,以确保编译器正确对端类型.

    @interface Airplane
    + (instancetype)airplaneWithType:(RWTAirplaneType)type;
    @end
    

    更多信息,详见 NSHipster.com

    <a name="cgrect-functions"></a>CGRect 函数

    获取x, y, width, or height of a CGRect, 用CGGeometry 函数 而不是struct成员。 Apple的 CGGeometry 提到:

    All functions described in this reference that take CGRect data structures as inputs implicitly standardize those rectangles before calculating their results. For this reason, your applications should avoid directly reading and writing the data stored in the CGRect data structure. Instead, use the functions described here to manipulate rectangles and to retrieve their characteristics.
    所有的CGRect 相关的值和函数都是需要算出来的。因此,你的应用应该避免直接读写 CGRect 内的数据,而是用以下方法获取相关值。

    推荐:

    CGRect frame = self.view.frame;
    
    CGFloat x = CGRectGetMinX(frame);
    CGFloat y = CGRectGetMinY(frame);
    CGFloat width = CGRectGetWidth(frame);
    CGFloat height = CGRectGetHeight(frame);
    CGRect frame = CGRectMake(0.0, 0.0, width, height);
    

    不推荐:

    CGRect frame = self.view.frame;
    
    CGFloat x = frame.origin.x;
    CGFloat y = frame.origin.y;
    CGFloat width = frame.size.width;
    CGFloat height = frame.size.height;
    CGRect frame = (CGRect){ .origin = CGPointZero, .size = frame.size };
    

    <a name="golden-path"></a>黄金路线

    条件语句提前返回。

    推荐:

    - (void)someMethod {
      if (![someOther boolValue]) {
        return;
      }
    
      //Do something important
    }
    

    不推荐:

    - (void)someMethod {
      if ([someOther boolValue]) {
        //Do something important
      }
    }
    

    <a name="error-handling"></a>Error 处理

    推荐:

    NSError *error;
    if (![self trySomethingWithError:&error]) {
      // Handle Error
    }
    

    不推荐:

    NSError *error;
    [self trySomethingWithError:&error];
    if (error) {
      // Handle Error
    }
    

    有些 Apple’s APIs 在successful cases时,将垃圾数据写入 error 中, 因此这样写会使判断错误或导致闪退。

    <a name="singletons"></a>单例

    创建线程安全的单例。

    + (instancetype)sharedInstance {
      static id sharedInstance = nil;
    
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
      });
    
      return sharedInstance;
    }
    

    这会阻止 可能的编译闪退

    <a name="line-breaks"></a>换行

    换行是重要的课题,主要是便于打印和浏览.

    如:

    self.productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
    

    两个空格的缩进

    self.productsRequest = [[SKProductsRequest alloc] 
      initWithProductIdentifiers:productIdentifiers];
    

    <a name="smiley-face"></a>笑脸

    推荐:

    :]
    

    不推荐:

    :)
    

    <a name="xcode-project"></a>Xcode 项目

    物理文件组织应该与 xcode 中的结构一致. Xcode groups 创建时应该映射到对应的文件系统. 可以以文件类型、特性将 group 分的更明确。

    如果可能,将所有 warning 视为 error additional warnings。 如果你想忽视 warnings ,可以参考Clang's pragma feature.

    其他编码规范

    如果我们的编码规范不符合您的风格,以下还有其他参考:

    相关文章

      网友评论

        本文标题:Objective-C 编码规范(中文)

        本文链接:https://www.haomeiwen.com/subject/yvsfjttx.html