目录

语言

用美式英语.

推荐:

UIColor *myColor = [UIColor whiteColor];

不推荐:

UIColor *myColour = [UIColor whiteColor];

代码组织

#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 {}

空格

  • 用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 被分别声明在不同行。
  • 避免冒号对其的写法. There are cases where a method signature may have >= 3 colons and colon-aligning makes the code more readable. Please do NOT however colon align methods containing blocks because Xcode's indenting makes it illegible.

推荐:

// 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
                 }];

注释

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

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

命名

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;

下划线

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

方法

方法签名中, 空格紧接着方法类型符号(-/+)。每段用空格分开(符合 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.

变量

变量命名应该具有描述性. 避免单个字如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;
}

属性

属性列表应该被明确列出,以便初学者识别。首先是 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;

.语法

.语法也调用了 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;

字面量

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];

常量

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

推荐:

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

static CGFloat const RWTImageThumbnailHeight = 50.0;

不推荐:

#define CompanyName @"RayWenderlich.com"

#define thumbnailHeight 2

枚举类型

枚举类型用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,
};

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;
}

私有属性

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

示例:

@interface RWTDetailViewController ()

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

@end

布尔值

Objective-C uses YES and NO. Therefore true and false should only be used for CoreFoundation, C or C++ code. Since nil resolves to NO it is unnecessary to compare it in conditions. Never compare something directly to YES, because YES is defined to 1 and a BOOL can be up to 8 bits.

This allows for more consistency across files and greater visual clarity.

推荐:

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

不推荐:

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

If the name of a BOOL property is expressed as an adjective, the property can omit the “is” prefix but specifies the conventional name for the get accessor, for example:

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

参考Cocoa Naming Guidelines

条件语句

Conditional bodies should always use braces even when a conditional body could be written without braces (e.g., it is one line only) to prevent errors. These errors include adding a second line and expecting it to be part of the if-statement. Another, even more dangerous defect may happen where the line "inside" the if-statement is commented out, and the next line unwittingly becomes part of the if-statement. In addition, this style is more consistent with all other conditionals, and therefore more easily scannable.

推荐:

if (!error) {
  return success;
}

不推荐:

if (!error)
  return success;

if (!error) return success;

三目运算符

The Ternary operator, ?: , should only be used when it increases clarity or code neatness. A single condition is usually all that should be evaluated. Evaluating multiple conditions is usually more understandable as an if statement, or refactored into instance variables. In general, the best use of the ternary operator is during assignment of a variable and deciding which value to use.

Non-boolean variables should be compared against something, and parentheses are added for improved readability. If the variable being compared is a boolean type, then no parentheses are needed.

推荐:

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

BOOL isHorizontal = YES;
result = isHorizontal ? x : y;

不推荐:

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

Init 方法

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

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

详见 类构造方法

类构造方法

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

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

更多信息,详见 NSHipster.com

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 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 };

黄金路线

条件语句提前返回。

推荐:

- (void)someMethod {
  if (![someOther boolValue]) {
    return;
  }

  //Do something important
}

不推荐:

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

Error 处理

推荐:

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

不推荐:

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

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

单例

创建线程安全的单例。

+ (instancetype)sharedInstance {
  static id sharedInstance = nil;

  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedInstance = [[self alloc] init];
  });

  return sharedInstance;
}

这会阻止 可能的编译闪退

换行

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

For example:

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

两个空格的缩进

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

笑脸

推荐:

:]

不推荐:

:)

Xcode 项目

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

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

其他编码规范

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

results matching ""

    No results matching ""