天天看点

iOS开发规范(OC)语言代码组织空格注释命名下划线方法变量属性特性点符号语法字面值常量枚举类型Case语句私有属性布尔值条件语句三元操作符Init方法类构造方法CGRect函数黄金路径错误处理单例模式换行符Xcode工程

语言

使用US英语

代码组织

在函数分组和

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

空格

  • 缩进使用4个空格,确保在Xcode偏好设置来设置
  • 方法大括号和其他大括号(

    if

    /

    else

    /

    switch

    /

    while

    等)总是在同一行语句打开但在新行中关闭。
  • 注释

    //

    后要有空格

应该:

if (user.isHappy) {
    // Do something  
} else {
    // Do something else  
}
           

不应该:

if (user.isHappy)
{
    //Do something  
}
else {
    //Do something else  
}
           
  • 在方法之间应该有且只有一行,这样有利于在视觉上更清晰和更易于组织。在方法内的空白应该分离功能,但通常都抽离出来成为一个新方法。
  • 优先使用auto-synthesis。但如果有必要,

    @synthesize

    @dynamic

    应该在实现中每个都声明新的一行。
  • 应该避免以冒号对齐的方式来调用方法。因为有时方法签名可能有3个以上的冒号和冒号对齐会使代码更加易读。请不要这样做,尽管冒号对齐的方法包含代码块,因为Xcode的对齐方式令它难以辨认。

应该:

// blocks are easily readable  
[UIView animateWithDuration: animations:^{  
  // something  
} completion:^(BOOL finished) {  
  // something  
}];
           

不应该:

// colon-aligning makes the block indentation hard to read  
[UIView animateWithDuration:  
                 animations:^{  
                     // something  
                 }  
                 completion:^(BOOL finished) {  
                     // something  
                 }];  
           

注释

  • 当需要注释时,注释应该用来解释这段特殊代码为什么要这样做。任何被使用的注释都必须保持最新或被删除。
  • 一般都避免使用块注释,因为代码尽可能做到自解释,只有当断断续续或几行代码时才需要注释。
  • 注释

    //

    后要有空格

应该:

不应该:

命名

Apple命名规则尽可能坚持,特别是与这些相关的memory management rules (NARC)。

长的,描述性的方法和变量命名是好的。

应该:

UIButton *settingsButton;  
           

不应该:

UIButton *setBut;  
           

三个字符前缀应该经常用在类和常量命名,但在Core Data的实体名中应被忽略。前缀’AN’应该被使用。

常量应该使用驼峰式命名规则,所有的单词首字母大写和加上与类名有关的前缀。

应该:

static NSTimeInterval const ANTutorialViewControllerNavigationFadeAnimationDuration = ;  
           

不应该:

static NSTimeInterval const fadetime = ;  
           

属性也是使用驼峰式,但首单词的首字母小写。对属性使用auto-synthesis,而不是手动编写

@synthesize

语句,除非你有一个好的理由。

应该:

@property (strong, nonatomic) NSString *descriptiveVariableName;  
           

不应该:

id varnm; 
           

下划线

  • 当使用属性时,实例变量应该使用

    self.

    来访问和改变。这就意味着所有属性将会视觉效果不同,因为它们前面都有

    self.

  • 但有一个特例:在初始化方法里,实例变量(例如,

    _variableName

    )应该直接被使用来避免

    getters

    /

    setters

    潜在的副作用。
  • 局部变量不应该包含下划线。

方法

  • 在方法签名中,应该在方法类型(

    -/+

    符号)之后有一个空格。在方法各个段之间应该也有一个空格(符合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()

    循环。
  • 星号表示变量是指针。例如,

    NSString *text

    既不是

    NSString* text

    也不是

    NSString * text

    ,除了一些特殊情况下常量。
  • 私有变量应该尽可能代替实例变量的使用。尽管使用实例变量是一种有效的方式,但更偏向于使用属性来保持代码一致性。
  • 通过使用

    back

    属性(

    _variable

    ,变量名前面有下划线)直接访问实例变量应该尽量避免,除了在初始化方法(

    init

    ,

    initWithCoder:

    , 等…),

    dealloc

    方法和自定义的

    setters

    getters

    。想了解关于如何在初始化方法和

    dealloc

    直接使用Accessor方法的更多信息,查看这里。

应该:

@interface ANTutorial : NSObject

@property (strong, nonatomic) NSString *tutorialName;

@end  
           

不应该:

@interface ANTutorial : 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;  
           

NSString

应该使用

copy

而不是

strong

的属性特性。

为什么?即使你声明一个

NSString

的属性,有人可能传入一个

NSMutableString

的实例,然后在你没有注意的情况下修改它。

应该:

@property (copy, nonatomic) NSString *tutorialName;  
           

不应该:

@property (strong, nonatomic) NSString *tutorialName;  
           

点符号语法

  • 点语法是一种很方便封装访问方法调用的方式。当你使用点语法时,通过使用

    getter

    setter

    方法,属性仍然被访问或修改。想了解更多,阅读这里。
  • 点语法应该总是被用来访问和修改属性,因为它使代码更加简洁。

    []

    符号更偏向于用在其他例子。

应该:

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

NSNumber

的字面值应该在创建这些类的不可变实例时被使用。

  • 请特别注意

    nil

    值不能传入

    NSArray

    NSDictionary

    字面值,因为这样会导致crash。

应该:

NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"];  
NSDictionary *productManagers = @{@"iPhone": @"Kate", @"iPad": @"Kamal", @"Mobile Web": @"Bill"};  
NSNumber *shouldUseLiterals = @YES;  
NSNumber *buildingStreetNumber = @;  
           

不应该:

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

常量

常量是容易重复被使用和无需通过查找和代替就能快速修改值。常量应该使用

static

来声明而不是使用

#define

,除非显式地使用宏。

应该:

static NSString * const ANAboutViewControllerCompanyName = @"xinshui.com";  
static CGFloat const ANImageThumbnailHeight = ;  
           

不应该:

#define CompanyName @"xinshui.com" 
#define thumbnailHeight 2  
           

枚举类型

当使用

enum

时,推荐使用新的固定基本类型规格,因为它有更强的类型检查和代码补全。现在SDK有一个宏

NS_ENUM()

来帮助和鼓励你使用固定的基本类型。

例如:

typedef NS_ENUM(NSInteger, ANLeftMenuTopItemType) {  
  ANLeftMenuTopItemMain,  
  ANLeftMenuTopItemShows,  
  ANLeftMenuTopItemSchedule  
}; 
           

你也可以显式地赋值(展示旧的

k-style

常量定义):

typedef NS_ENUM(NSInteger, ANGlobalConstants) {  
  ANPinSizeMin = ,  
  ANPinSizeMax = ,  
  ANPinCountMin = ,  
  ANPinCountMax = ,  
}; 
           

旧的

k-style

常量定义应该避免除非编写Core Foundation C的代码。

不应该:

enum GlobalConstants {  
  kMaxPinSize = ,  
  kMaxPinCount = ,  
}; 
           

Case语句

大括号在

case

语句中并不是必须的,除非编译器强制要求。当一个

case

语句包含多行代码时,大括号应该加上。

switch (condition) {  
  case :  
    // ...  
    break;  
  case : {  
    // ...  
    // Multi-line example using braces  
    break;  
  }  
  case :  
    // ...  
    break;  
  default:   
    // ...  
    break;  
}  
           

有很多次,当相同代码被多个

cases

使用时,一个

fall-through

应该被使用。一个

fall-through

就是在

case

最后移除

break

语句,这样就能够允许执行流程跳转到下一个

case

值。为了代码更加清晰,一个

fall-through

需要注释一下。

switch (condition) {  
  case :  
    // fall-through!
  case :  
    // code executed for values  and   
    break;  
  default:   
    // ...  
    break;  
}  
           

当在

switch

使用枚举类型时,

default

是不需要的。

例如:

ANLeftMenuTopItemType menuType = ANLeftMenuTopItemMain;  
switch (menuType) {  
  case ANLeftMenuTopItemMain:  
    // ...  
    break;  
  case ANLeftMenuTopItemShows:  
    // ...  
    break;  
  case ANLeftMenuTopItemSchedule:  
    // ...  
    break;  
}  
           

私有属性

私有属性应该在类的实现文件中的类扩展(匿名分类)中声明,命名分类(比如

ANPrivate

private

)应该从不使用除非是扩展其他类。匿名分类应该通过使用

<headerfile>+Private.h

文件的命名规则暴露给测试。

例如:

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

布尔值

Objective-C使用

YES

NO

。因为

true

false

应该只在CoreFoundation,C或C++代码使用。既然

nil

解析成NO,所以没有必要在条件语句比较。不要拿某样东西直接与

YES

比较,因为

YES

被定义为

1

和一个

BOOL

能被设置为8位。

  • 这是为了在不同文件保持一致性和在视觉上更加简洁而考虑。

应该:

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

不应该:

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

如果

BOOL

属性的名字是一个形容词,属性就能忽略is前缀,但要指定

get

访问器的惯用名称。

例如:

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

文字和例子从这里引用Cocoa Naming Guidelines。

条件语句

条件语句主体为了防止出错应该使用大括号包围,即使条件语句主体能够不用大括号编写(如,只用一行代码)。这些错误包括添加第二行代码和期望它成为

if

语句;还有,even more dangerous defect可能发生在

if

语句里面一行代码被注释了,然后下一行代码不知不觉地成为

if

语句的一部分。除此之外,这种风格与其他条件语句的风格保持一致,所以更加容易阅读。

应该:

if (!error) {  
  return success;  
}  
           

不应该:

if (!error)  
  return success;  
           
if (!error) return success;  
           

三元操作符

当需要提高代码的清晰性和简洁性时,三元操作符

?:

才会使用。单个条件求值常常需要它。多个条件求值时,如果使用if语句或重构成实例变量时,代码会更加易读。一般来说,最好使用三元操作符是在根据条件来赋值的情况下。

Non-boolean

的变量与某东西比较,加上括号

()

会提高可读性。如果被比较的变量是

boolean

类型,那么就不需要括号。

应该:

NSInteger value = ;  
result = (value != ) ? 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:(ANAirplaneType)type;  
@end  
           

关于更多

instancetype

信息,请查看NSHipster.com。

CGRect函数

当访问

CGRect

里的

x

,

y

,

width

,或

height

时,应该使用

CGGeometry

函数而不是直接通过结构体来访问。引用Apple的CGGeometry:

在这个参考文档中所有的函数,接受

CGRect

结构体作为输入,在计算它们结果时隐式地标准化这些rectangles。因此,你的应用程序应该避免直接访问和修改保存在

CGRect

数据结构中的数据。相反,使用这些函数来操纵rectangles和获取它们的特性。

应该:

CGRect frame = self.view.frame;  
CGFloat x = CGRectGetMinX(frame);  
CGFloat y = CGRectGetMinY(frame);  
CGFloat width = CGRectGetWidth(frame);  
CGFloat height = CGRectGetHeight(frame);  
CGRect frame = CGRectMake(, , 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 };  
           

黄金路径

当使用条件语句编码时,左手边的代码应该是”golden” 或 “happy”路径。也就是不要嵌套if语句,多个返回语句也是OK。

应该:

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

不应该:

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

错误处理

当方法通过引用来返回一个错误参数,判断返回值而不是错误变量。

应该:

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

不应该:

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

在成功的情况下,有些Apple的APIs记录垃圾值

(garbage values)

到错误参数(如果

non-NULL

),那么判断错误值会导致

false``负值

和crash。

单例模式

单例对象应该使用线程安全模式来创建共享实例。

+ (instancetype)sharedInstance {  
  static id sharedInstance = nil;  
  static dispatch_once_t onceToken;  
  dispatch_once(&onceToken, ^{  
    sharedInstance = [[self alloc] init];  
  });  
  return sharedInstance;  
}  
           

这会防止possible and sometimes prolific crashes。

换行符

换行符是一个很重要的主题,因为它的风格指南主要为了打印和网上的可读性。

例如:

一行很长的代码应该分成两行代码,下一行用两个空格隔开。

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

Xcode工程

物理文件应该与Xcode工程文件保持同步来避免文件扩张。任何Xcode分组的创建应该在文件系统的文件体现。代码不仅是根据类型来分组,而且还可以根据功能来分组,这样代码更加清晰。