介绍
这里编码规范有可能与你看到的其他Objective-C编码规范不同,因为它主要是为了打印和Web的易读性。
我们也非常感谢New York Times 和Robots & Pencils'Objective-C编码规范的作者。这两个编码规范为本指南的创建提供很好的起点。
这里有些关于编码风格Apple官方文档,如果有些东西没有提及,可以在以下文档来查找更多细节:
应该使用US英语。
不应该:
UIColor *myColour = [UIColor whiteColor];
在函数分组和protocol/delegate实现中使用#pragma mark -来分类方法,要遵循以下一般结构:
#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 {}应该:
if (user.isHappy) { //Do something} else { //Do something else}应该:
// blocks are easily readable[UIView animateWithDuration:1.0 animations:^{ // something} completion:^(BOOL finished) { // something}];注释
一般都避免使用块注释,因为代码尽可能做到自解释,只有当断断续续或几行代码时才需要注释。例外:这不应用在生成文档的注释
Apple命名规则尽可能坚持,特别是与这些相关的memory management rules(NARC)。
应该:
UIButton *settingsButton;
三个字符前缀应该经常用在类和常量命名,但在Core Data的实体名中应被忽略。对于官方的raywenderlich.com书、初学者工具包或教程,前缀'RWT'应该被使用。
应该:
static NSTimeInterval const RWTTutorialViewControllerNavigationFadeAnimationDuration = 0.3;
属性也是使用驼峰式,但首单词的首字母小写。对属性使用auto-synthesis,而不是手动编写@synthesize语句,除非你有一个好的理由。
不应该:
id varnm;
