Objective-C 编码规范(中文)

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

简介

本代码规范旨在保持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.

其他编码规范

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容