iOS开发中 常见的编码规范(整理及补充)

前沿

    开发中的编码规范,个人感觉是很重要的,这涉及到协作问题;但是代码规范涉及到方方面面,这里只着重介绍本人在真实的项目开发中所用到的东西以及归纳总结了国内外相应的文章,若有写的不好地方,请个人看官留留言,我本人也好进行相应的修改并学习!

命名规范

驼峰命名法

  • 属性、变量、方法均使用小写字母开发头的驼峰命名方式,全局变量命名,以小写字母开头;
static NSString *dataNormal = nil;// good
static NSString *datanormal = nil;// avoid

特有的前缀命名方式

  • 类名、协议名、枚举类型、宏统一以项目前缀开头,项目前缀为2-3个大写字母,例如本文档以XI(CodeStyle缩写)作为项目前缀;
@interface XIBaseViewController : UIViewController
@end
  • 避免使用以“”开头的实例变量,直接使用属性替代实例变量,私有方法也不能以“”开头,因为这是C++标准,且“_”前缀是Apple保留的,不要重载苹果的私有方法,以免在Apple审核的时候被拒绝。
@interface ViewController () {
    BOOL _hasViewed; // avoid
}
@property (nonatomic, assign) BOOL isToday; // good
@end
  • 执行性的方法以动词开头,返回性的方法以返回内容开头,但之前不要加get,避免方法名和声明的属性的getter发生冲突;一般我在项目开发中的话会汉译英的方法名,并且以驼峰命名的方式进行;
  - (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject; // 执行性,good
+ (id)arrayWithArray:(NSArray *)array; // 返回性,good
+ (id)getArrayWithArray:(NSArray *)array; // 返回性,avoid

代码格式

空格

  • 在指针”*”号的位置在变量名前,而非变量类型之后,与变量名无空格相连,与类型间有个空格;
 @property (nonatomic, strong) NSString* name;  //avoid
 @property (nonatomic, strong) NSString *password;  //good
  • “{“和”(“前均需要一个空格,“}”后如果紧跟着内容比如else,也需要一个空格,但“(”和“[”右边,“)”和“]”左边不能有空格。涉及位置:if-else,while,方法声明在@interface和实现在@implementation。
-(void)viewDidLoad{ // avoid
    [super viewDidLoad];
    if([self isOk]){ // avoid
        // ...
    }else{ // avoid
        // ...
    }
}

- (void)viewDidLoad { // good
    [super viewDidLoad];
    if ([self isOk]) { // good
        // ...
    } else { // good
        // ...
    }
}
  • 除了++和–外的运算符前后均需要一个空格;
 if ( i>10 ) { // avoid
        i ++; // avoid
    } else {
        i+=2; // avoid
    }

    // good
    if (i > 10) {
        i++;
    } else {
        i += 2;
    }
  • “,”左边不留空格,右边空一格
@property (nonatomic,readonly ,strong) NSString* name;// avoid

NSArray *array = @[@"A" , @"B" ,@"C"]; // avoid

@property (nonatomic, readonly, strong) NSString* name; // good

NSArray *array = @[@"A", @"B", @"C"]; // good

括号

  • if、else后面必须紧跟”{ }”,即便只有一行代码。
    防止之后增添逻辑时忽略增加{},逻辑代码跑到if、else之外,同时更便于阅读。
   if (i > 10) // avoid
        i++;
    else
        i--;

    if (i > 10) { // good
        i++;
    } else {
        i--;
    }

  if (i > 10) return; //good
  个人:因为return为关键字,有很醒目的标示,所以这里我赞同这样的写法
  注: 花括号"{}"统一不另其一行,else之间是有空格的
// avoid
- (void)test
{
    if ([self isOK])
    {
        // ...
    }
    else
    {
        // ...
    }
}


// good
- (void)test {
    if ([self isOK]) {
        // ...
    } else {
        // ...
    }
}

注: ifelse两边的空格,void+"{",而不另起一行来书写"{}",主要是为了减少代码的冗余。逻辑结构看起来更加清晰明了;

属性

  • 直接使用@property来替代实例变量,非特殊情况不使用 @synthesize 和 @dynamic

  • @property括号内的描述性修饰符,严格按以下顺序书写:原子性,读写(一般为封装私有类,不让外界更改其属性等的操作会readOnly),内存管理。

// avoid
@property (copy, nonatomic, readonly) NSString *name;
@property (nonatomic, assign, readonly) NSInteger age;
@property (readwrite, strong, nonatomic) XICard *card;

// good
@property (nonatomic, readonly, copy) NSString *name;
@property (nonatomic, readonly, assign) NSInteger age;
@property (nonatomic, readwrite, strong) XICard *card;

注: 因为三种描述符经常需要修改,属性与属性间差异比较大的是内存管理(iOS6 过后,也就是ARC开始,内存不用手动释放),其次才是读写和原子性,方便从右往左修改,也能让代码前部分较美观地对齐。
  • 不可变类型,但可被可变类型(Mutable)对象赋值的属性,例如:NSString、NSArray、NSDictionary、NSURLRequest,其内存管理属性类型必须为copy。
    @property (nonatomic, copy) NSString *name; // good

    NSMutableString * name = [[NSMutableString alloc] initWithString:@"User1"];
    XIUserModel *user = [XIUserModel new];
    user.name = name;
    [name appendString:@"0"];
    NSLog(@"%@", user.name); // output:User1


    @property (nonatomic, strong) NSString *name; // avoid

    NSMutableString * name = [[NSMutableString alloc] initWithString:@"User1"];
    XIUserModel *user = [XIUserModel new];
    user.name = name;
    [name appendString:@"0"];
    NSLog(@"%@", user.name); // output:User10, Something Wrong!
注:以防止声明的不可变的属性,实际赋值的是一个可变对象,对象内容还在不知情的情况下被外部修改。
  • 避免在类的头文件中暴露可变对象,建议提供readonly内存管理和使用不可变对象,以防止外部调用者改变内部表示,破坏封装性。
  • 避免在init和dealloc中使用点语法访问属性,这两个地方需要直接访问”_”开头的实例变量。

    因为init中访问setter或getter,可能访问到的是子类重写后的方法,而方法内使用了其它未初始化或不稳定的属性或访问了其它方法,导致期望之外的情况发生。注:仅当init返回后,才标识着一个对象完成初始化可使用。
    在dealloc方法中,对象处于释放前不稳定状态,访问setter、getter可能出现问题。

  • 属性建议采用点语法访问,以和方法调用区分开来。但是对于重写了setter、getter的属性,可以方法调用方式访问,以告诉代码阅读者访问的该setter、getter是重写过,可能带有副作用的。

  • if 在进行比较的时候,在它的括号内不使用nil、NO或YES

 if (obj == nil && finish == YES && result == NO){ // avoid

    } 
    if(!obj && finish && !result){ // good

    }
  • 尽量减少@throw、@try、@catch、@finally的使用,会影响性能,使用常量替代代码中固定的字符串和数字,以方便理解、查找和替换。

  • 常量在实际开发中建议使用static声明为静态常量,内存只分配一次,#define尽量不考虑,除非有特殊的情况下;

换行

  • 避免使用两行以上的空行,建议#import、@interface、@implementation、方法与方法之间以两行空行作为间隔。
#import "MyFirst.h" // good

#import "MySecond.h"   //good

#import "MyFirst.h" //avoid
#import "MySecond.h" //avoid
  • 方法内可使用一行空行来分离不同功能的代码块,但通常不同功能代码块应该考虑抽取新的方法。

  • 包含3个及以上参数的方法签名,建议对每个参数进行换行并参数与类型一一对齐,参数按照冒号对其,让代码具有更好可读性,也便于修改。

// avoid
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion {
    // ...
}

// good
+ (void)animateWithDuration:(NSTimeInterval)duration
                 animations:(void (^)(void))animations
                 completion:(void (^)(BOOL finished))completion {
    // ...
}

注释
- 单行注释: “//”之后空一格,再写具体注释内容,如果“//”注释与代码在同一行,则代码最后一个字符空一格,再写注释;

// avoid
- (void)test {
    //Just For Debug
    BOOL isTest = YES;//Main Logic
    //...
}

// good
 - (void)test {
    // Just For Debug
    BOOL isTest = YES; // Main Logic
    // ...
}
  • 对方法签名使用多行注释,按照Xocde风格“Editor-Structure-Add
    Document”添加。Description部分,第一行用最简单语句描述方法作用,如需详细说明,则空一行后,再进行详细描述。快捷键:‘Command + alt + ‘/’ ”;
/**
 描述方法的用途
 */
- (void)voidTestNoParams{
    // ...

}


/**
 描述方法用途

 @param str 参数作用、代表什么意思
 */
- (void)voidTesthaveParamsWithString:(NSString *)str{
  // ...

}

代码组织结构

#pragma

  • 对一个文件中的代码使用“#pragma mark - CodeBlockName”进行分段,易于代码维护和阅读。常用的开发中我们会进行分段并分类,统一管理一个模块功能;
    常见的书写方式如下:
- (void)dealloc { /* ... */ }
- (instancetype)init { /* ... */ }

#pragma mark - View Lifecycle
- (void)viewDidLoad { /* ... */ }
- (void)didReceiveMemoryWarning { /* ... */ }

#pragma mark - Setter Getter
- (void)setCustomProperty:(id)value { /* ... */ }
- (id)customProperty { /* ... */ }

#pragma mark - IBActions
- (IBAction)onOkButtonClick:(id)sender { /* ... */ }

#pragma mark - Public
- (void)publicMethod { /* ... */ }

#pragma mark - Private
- (void)privateMethod { /* ... */ }

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { /* ... */ }

#pragma mark - Superclass
- (void)superClassMethod { /* ... */ }

#pragma mark - NSObject
 - (NSString *)description { /* ... */ }
  • @interface声明实现的协议时,一条协议占用一行,@interface所在行不书写协议名换行书写。以便于阅读和修改。
// avoid
@interface HelpLookMessage  ()<HelpTitleViewDelegate,UITableViewDelegate,UITableViewDataSource,HeadViewDelegate>
@end


@interface HelpLookMessage () // good
<HelpTitleViewDelegate,
UITableViewDelegate,
UITableViewDataSource,
HeadViewDelegate>
@end
  • dealloc方法的实现(在控制器销毁的时候会调用这个方法),需要放在文件最前面,一般在@implementation之后,在init或viewDidLoad之前,以便于检查。

  • 当主逻辑代码的执行,需要满足多个条件时,避免if语句嵌套,此时使用return语句可减少if嵌套降低循环复杂度,将条件和主逻辑清楚地区分开。

// avoid
- (void)method {
    if ([self conditionA]) {
        // some code..
        if ([self conditionB]) {
            // main logic...
        }
    }
}

// good
- (void)methodB { // 括号、空格等书写方式
    if (![self conditionA]) {
        return;
    }

    if (![self conditionB]) {
        return;
    }

    // some codeA..
    // main logic...
}

接口规范

  • 保持公有API简明:对于不想公开的方法和属性,只在.m文件中声明实现,.h文件中仅声明必须公开的方法/属性。

  • 委托模式中声明的@protocol名称,需要以委托类名(比如UITableView)开头,之后加上“Delegate”或“Protocol”。

  • @protocol内声明的方法,需要以委托类名去除项目前缀后的单词开头,并且第一个参数需要为委托对象,否则被委托类代理了多个委托时,无法区分该委托方法是由哪个委托对象发起的。

    @class XIShareViewController;

    @protocol XIShareDelegate <NSObject> // avoid

    - (void)shareFinished:(BOOL)isSuccess; // avoid

    @end


   @class XIShareViewController;

   @protocol XIShareViewControllerDelegate <NSObject> // good

    - (void)shareViewController:(XIShareViewController *)shareViewController // good
shareFinished:(BOOL)isSuccess;

    @end
  • 抛出error的方法,应该有BOOL返回值表示方法主功能逻辑成功与否。使用该类接口先检查方法返回值,再依据error进行相应的处理。苹果API有在成功情况下依旧往error写入垃圾数据的情况。
// avoid
- (void)methodWithError:(NSError **)error {
    // ...
}

- (void)test1 {
    NSError *error = nil;
    if ([self methodWithError:&error]) { // avoid
        // Main Logic
    } else {
        // Handle Error
    }
}

// good
- (BOOL)methodWithError:(NSError **)error {
    // ...
}
- (void)test {
    NSError *error = nil;
    if ([self methodWithError:&error]) { // good
        // Main Logic
    } else {
        // Handle Error
    }
}

猜你喜欢

转载自blog.csdn.net/whjay520/article/details/77648224