Objective-C编码规范精选

栏目: Objective-C · 发布时间: 6年前

内容简介:Objective-C编码规范精选

代码不仅是可以编译的,同时应该是 “有效” 的。好的代码有一些特性:简明,自我解释,优秀的组织,良好的文档,良好的命名,优秀的设计以及可以被久经考验。 ——《禅与 Objective-C 编程艺术》

依据日常个人和团队编码习惯总结、挑选出几点Objective-C代码规范,整理出此文,持续更新。

多条规范和思路参考 《禅与 Objective-C 编程艺术》 一书,非常推荐一读。

命名规范

驼峰命名

  • 属性、变量、方法(iOS中的方法,规范的名称应该是:消息)均使用小写字母开头的驼峰命名。
  • 全局变量命名,以小写字母g开头。
static CSDataManager *gDataManager = nil; // good
static CSDataManager *dataManager = nil; // avoid

前缀

  • 类名、协议名、枚举类型、宏统一以项目前缀开头,项目前缀为2-3个大写字母,例如本文档以CS(CodeStyle缩写)作为项目前缀。
@interface OCBaseViewController : UIViewController
@end
  • 避免使用以“_”开头的实例变量,直接使用属性替代实例变量。
@interface ViewController () {
    BOOL _hasViewed; // avoid
}
@property (nonatomic, assign) BOOL isToday; // good
@end
  • 私有方法也不能以“_”开头,因为这是C++标准,且“_”前缀是Apple保留的,不要冒重载苹果的私有方法的险。 可借助 #pragma 在代码块中区分私有方法。
- (void)_privateMethod { // avoid
}

#pragma mark - Private Method

- (void)privateMethod { // good
}
  • 执行性的方法以动词开头,返回性的方法以返回内容开头,但之前不要加get
- (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等。
-(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-else中,else不另起一行,与if的反括号在同一行,如上段代码所示,注意else前后均有空格。
  • 花括号统一采用不换行风格。 涉及位置:@interface、方法实现、if-else、switch-case等。 优点: 减少代码冗余行数,代码更加紧凑,结构清晰。
// avoid

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


// good

- (void)test {
    if ([self isOK]) {
        // ...
    } else {
        // ...
    }
}
  • switch-case中,case后的代码多余一行,则需要{}包裹,建议所有case和default后的代码块均用{}包裹。

属性

  • 直接使用@property来替代实例变量,非特殊情况不使用 @synthesize 和 @dynamic
  • @property括号内的描述性修饰符,严格按以下顺序书写: 原子性,读写,内存管理 。 因为三种描述符经常需要修改,属性与属性间差异比较大的是内存管理,其次才是读写和原子性,方便从右往左修改,也能让代码前部分较美观地对齐。
// avoid
@property (copy, nonatomic, readonly) NSString *name;
@property (nonatomic, assign, readonly) NSInteger age;
@property (readwrite, strong, nonatomic) CSCard *card;

// good
@property (nonatomic, readonly, copy) NSString *name;
@property (nonatomic, readonly, assign) NSInteger age;
@property (nonatomic, readwrite, strong) CSCard *card;
  • 不可变类型,但可被可变类型(Mutable)对象赋值的属性,例如:NSString、NSArray、NSDictionary、NSURLRequest,其内存管理属性类型必须为 copy 。 以防止声明的不可变的属性,实际赋值的是一个可变对象,对象内容还在不知情的情况下被外部修改。
@property (nonatomic, copy) NSString *name; // good

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


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

    NSMutableString * name = [[NSMutableString alloc] initWithString:@"User1"];
    CSUserModel *user = [CSUserModel 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、方法与方法之间以两行空行作为间隔。
  • 方法内可使用一行空行来分离不同功能的代码块,但通常不同功能代码块应该考虑抽取新的方法。
  • 包含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部分,第一行用最简单语句描述方法作用,如需详细说明,则空一行后,再进行详细描述。
/**
 执行xxx操作,可能失败。

 xxxxxxxxxxxxxxxxxx
 xxxxxxxxxxxxxxxxxx
 xxxxxxxxxxxxxxxxxx(具体使用事项)

 @param error NSError,-1:xxx;-2:xxxxx
 */
- (void)methodWithError:(NSError **)error {
    // ...
}

代码组织

#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 CodeStyleViewController () <UITableViewDelegate, UITableViewDataSource, UIActionSheetDelegate>
@end

// good
@interface CSViewController () <
UITableViewDelegate,
UITableViewDataSource,
UIActionSheetDelegate
>
@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 CSShareViewController;
@protocol CSShareDelegate <NSObject> // avoid

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

@end



@class CSShareViewController;
@protocol CSShareViewControllerDelegate <NSObject> // good

- (void)shareViewController:(CSShareViewController *)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
    }
}

以上所述就是小编给大家介绍的《Objective-C编码规范精选》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

解密搜索引擎技术实战

解密搜索引擎技术实战

罗刚 / 2011-6 / 69.80元

《解密搜索引擎技术实战-Lucene&Java精华版(附盘)》,本书主要包括总体介绍部分、爬虫部分、自然语言处理部分、全文检索部分以及相关案例分析。爬虫部分介绍了网页遍历方法和如何实现增量抓取,并介绍了从网页等各种格式的文档中提取主要内容的方法。自然语言处理部分从统计机器学习的原理出发,包括了中文分词与词性标注的理论与实现以及在搜索引擎中的实用等细节,同时对文档排重、文本分类、自动聚类、句法分析树......一起来看看 《解密搜索引擎技术实战》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

MD5 加密
MD5 加密

MD5 加密工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具