iOS编码规范

The official raywenderlich.com Objective-C style guide.

This style guide outlines the coding conventions for raywenderlich.com.

Introduction

The reason we made this style guide was so that we could keep the code in our books, tutorials, and starter kits nice and consistent - even though we have many different authors working on the books.

This style guide is different from other Objective-C style guides you may see, because the focus is centered on readability for print and the web. Many of the decisions were made with an eye toward conserving space for print, easy legibility, and tutorial writing.

Credits

The creation of this style guide was a collaborative effort from variousraywenderlich.com team members under the direction of Nicholas Waynik. The team includes: Soheil Moayedi AzarpourRicardo Rendon CepedaTony DahburaColin EberhardtMatt GallowayGreg HeoMatthijs HollemansChristopher LaPolloSaul MoraAndy PereiraMic PringlePietro ReaCesare RocchiMarin TodorovNicholas Waynik, and Ray Wenderlich

We would like to thank the creators of the New York Times and Robots & Pencils‘ Objective-C Style Guides. These two style guides provided a solid starting point for this guide to be created and based upon.

Background

Here are some of the documents from Apple that informed the style guide. If something isn‘t mentioned here, it‘s probably covered in great detail in one of these:

Table of Contents

Language

US English should be used.

Preferred:

UIColor *myColor = [UIColor whiteColor];

Not Preferred:

UIColor *myColour = [UIColor whiteColor];

Code Organization

Use #pragma mark - to categorize methods in functional groupings and protocol/delegate implementations following this general structure.

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

Spacing

  • Indent using 2 spaces (this conserves space in print and makes line wrapping less likely). Never indent with tabs. Be sure to set this preference in Xcode.
  • Method braces and other braces (if/else/switch/while etc.) always open on the same line as the statement but close on a new line.

Preferred:

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

Not Preferred:

if (user.isHappy)
{
    //Do something
}
else {
    //Do something else
}
  • There should be exactly one blank line between methods to aid in visual clarity and organization. Whitespace within methods should separate functionality, but often there should probably be new methods.
  • Prefer using auto-synthesis. But if necessary, @synthesize and @dynamic should each be declared on new lines in the implementation.
  • Colon-aligning method invocation should often be avoided. 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.

Preferred:

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

Not Preferred:

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

Comments

When they are needed, comments should be used to explain why a particular piece of code does something. Any comments that are used must be kept up-to-date or deleted.

Block comments should generally be avoided, as code should be as self-documenting as possible, with only the need for intermittent, few-line explanations. Exception: This does not apply to those comments used to generate documentation.

Naming

Apple naming conventions should be adhered to wherever possible, especially those related tomemory management rules(NARC).

Long, descriptive method and variable names are good.

Preferred:

UIButton *settingsButton;

Not Preferred:

UIButton *setBut;

A three letter prefix should always be used for class names and constants, however may be omitted for Core Data entity names. For any official raywenderlich.com books, starter kits, or tutorials, the prefix ‘RWT‘ should be used.

Constants should be camel-case with all words capitalized and prefixed by the related class name for clarity.

Preferred:

static NSTimeInterval const RWTTutorialViewControllerNavigationFadeAnimationDuration = 0.3;

Not Preferred:

static NSTimeInterval const fadetime = 1.7;

Properties should be camel-case with the leading word being lowercase. Use auto-synthesis for properties rather than manual @synthesize statements unless you have good reason.

Preferred:

@property (strong, nonatomic) NSString *descriptiveVariableName;

Not Preferred:

id varnm;

Underscores

When using properties, instance variables should always be accessed and mutated using self.. This means that all properties will be visually distinct, as they will all be prefaced with self..

An exception to this: inside initializers, the backing instance variable (i.e. _variableName) should be used directly to avoid any potential side effects of the getters/setters.

Local variables should not contain underscores.

Methods

In method signatures, there should be a space after the method type (-/+ symbol). There should be a space between the method segments (matching Apple‘s style). Always include a keyword and be descriptive with the word before the argument which describes the argument.

The usage of the word "and" is reserved. It should not be used for multiple parameters as illustrated in the initWithWidth:height: example below.

Preferred:

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

Not Preferred:

-(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.

Variables

Variables should be named as descriptively as possible. Single letter variable names should be avoided except in for()loops.

Asterisks indicating pointers belong with the variable, e.g., NSString *text not NSString* text or NSString * text, except in the case of constants.

Private properties should be used in place of instance variables whenever possible. Although using instance variables is a valid way of doing things, by agreeing to prefer properties our code will be more consistent.

Direct access to instance variables that ‘back‘ properties should be avoided except in initializer methods (initinitWithCoder:, etc…), dealloc methods and within custom setters and getters. For more information on using Accessor Methods in Initializer Methods and dealloc, see here.

Preferred:

@interface RWTTutorial : NSObject

@property (strong, nonatomic) NSString *tutorialName;

@end

Not Preferred:

@interface RWTTutorial : NSObject {
  NSString *tutorialName;
}

Property Attributes

Property attributes should be explicitly listed, and will help new programmers when reading the code. The order of properties should be storage then atomicity, which is consistent with automatically generated code when connecting UI elements from Interface Builder.

Preferred:

@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (strong, nonatomic) NSString *tutorialName;

Not Preferred:

@property (nonatomic, weak) IBOutlet UIView *containerView;
@property (nonatomic) NSString *tutorialName;

Properties with mutable counterparts (e.g. NSString) should prefer copy instead of strong. Why? Even if you declared a property as NSString somebody might pass in an instance of an NSMutableString and then change it without you noticing that.

Preferred:

@property (copy, nonatomic) NSString *tutorialName;

Not Preferred:

@property (strong, nonatomic) NSString *tutorialName;

Dot-Notation Syntax

Dot syntax is purely a convenient wrapper around accessor method calls. When you use dot syntax, the property is still accessed or changed using getter and setter methods. Read morehere

Dot-notation should always be used for accessing and mutating properties, as it makes code more concise. Bracket notation is preferred in all other instances.

Preferred:

NSInteger arrayCount = [self.array count];
view.backgroundColor = [UIColor orangeColor];
[UIApplication sharedApplication].delegate;

Not Preferred:

NSInteger arrayCount = self.array.count;
[view setBackgroundColor:[UIColor orangeColor]];
UIApplication.sharedApplication.delegate;

Literals

NSStringNSDictionaryNSArray, and NSNumber literals should be used whenever creating immutable instances of those objects. Pay special care that nil values can not be passed into NSArray and NSDictionary literals, as this will cause a crash.

Preferred:

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

Not Preferred:

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

Constants

Constants are preferred over in-line string literals or numbers, as they allow for easy reproduction of commonly used variables and can be quickly changed without the need for find and replace. Constants should be declared as staticconstants and not #defines unless explicitly being used as a macro.

Preferred:

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

static CGFloat const RWTImageThumbnailHeight = 50.0;

Not Preferred:

#define CompanyName @"RayWenderlich.com"

#define thumbnailHeight 2

Enumerated Types

When using enums, it is recommended to use the new fixed underlying type specification because it has stronger type checking and code completion. The SDK now includes a macro to facilitate and encourage use of fixed underlying types: NS_ENUM()

For Example:

typedef NS_ENUM(NSInteger, RWTLeftMenuTopItemType) {
  RWTLeftMenuTopItemMain,
  RWTLeftMenuTopItemShows,
  RWTLeftMenuTopItemSchedule
};

You can also make explicit value assignments (showing older k-style constant definition):

typedef NS_ENUM(NSInteger, RWTGlobalConstants) {
  RWTPinSizeMin = 1,
  RWTPinSizeMax = 5,
  RWTPinCountMin = 100,
  RWTPinCountMax = 500,
};

Older k-style constant definitions should be avoided unless writing CoreFoundation C code (unlikely).

Not Preferred:

enum GlobalConstants {
  kMaxPinSize = 5,
  kMaxPinCount = 500,
};

Case Statements

Braces are not required for case statements, unless enforced by the complier.
When a case contains more than one line, braces should be added.

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

There are times when the same code can be used for multiple cases, and a fall-through should be used. A fall-through is the removal of the ‘break‘ statement for a case thus allowing the flow of execution to pass to the next case value. A fall-through should be commented for coding clarity.

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

When using an enumerated type for a switch, ‘default‘ is not needed. For example:

RWTLeftMenuTopItemType menuType = RWTLeftMenuTopItemMain;

switch (menuType) {
  case RWTLeftMenuTopItemMain:
    // ...
    break;
  case RWTLeftMenuTopItemShows:
    // ...
    break;
  case RWTLeftMenuTopItemSchedule:
    // ...
    break;
}

Private Properties

Private properties should be declared in class extensions (anonymous categories) in the implementation file of a class. Named categories (such as RWTPrivate or private) should never be used unless extending another class. The Anonymous category can be shared/exposed for testing using the +Private.h file naming convention.

For Example:

@interface RWTDetailViewController ()

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

@end

Booleans

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.

Preferred:

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

Not Preferred:

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;

Text and example taken from theCocoa Naming Guidelines.

Conditionals

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.

Preferred:

if (!error) {
  return success;
}

Not Preferred:

if (!error)
  return success;

or

if (!error) return success;

Ternary Operator

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.

Preferred:

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

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

Not Preferred:

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

Init Methods

Init methods should follow the convention provided by Apple‘s generated code template. A return type of ‘instancetype‘ should also be used instead of ‘id‘.

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

SeeClass Constructor Methods for link to article on instancetype.

Class Constructor Methods

Where class constructor methods are used, these should always return type of ‘instancetype‘ and never ‘id‘. This ensures the compiler correctly infers the result type.

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

More information on instancetype can be found onNSHipster.com.

CGRect Functions

When accessing the xywidth, or height of a CGRect, always use theCGGeometry functions instead of direct struct member access. From Apple‘s CGGeometry reference:

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.

Preferred:

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

Not Preferred:

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 Path

When coding with conditionals, the left hand margin of the code should be the "golden" or "happy" path. That is, don‘t nest if statements. Multiple return statements are OK.

Preferred:

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

  //Do something important
}

Not Preferred:

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

Error handling

When methods return an error parameter by reference, switch on the returned value, not the error variable.

Preferred:

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

Not Preferred:

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

Some of Apple’s APIs write garbage values to the error parameter (if non-NULL) in successful cases, so switching on the error can cause false negatives (and subsequently crash).

Singletons

Singleton objects should use a thread-safe pattern for creating their shared instance.

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

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

  return sharedInstance;
}

This will preventpossible and sometimes prolific crashes.

Line Breaks

Line breaks are an important topic since this style guide is focused for print and online readability.

For example:

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

A long line of code like this should be carried on to the second line adhering to this style guide‘s Spacing section (two spaces).

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

Smiley Face

Smiley faces are a very prominent style feature of theraywenderlich.com site! It is very important to have the correct smile signifying the immense amount of happiness and excitement for the coding topic. The end square bracket is used because it represents the largest smile able to be captured using ascii art. A half-hearted smile is represented if an end parenthesis is used, and thus not preferred.

Preferred:

:]

Not Preferred:

:)

Xcode project

The physical files should be kept in sync with the Xcode project files in order to avoid file sprawl. Any Xcode groups created should be reflected by folders in the filesystem. Code should be grouped not only by type, but also by feature for greater clarity.

When possible, always turn on "Treat Warnings as Errors" in the target‘s Build Settings and enable as manyadditional warnings as possible. If you need to ignore a specific warning, use Clang‘s pragma feature.

Other Objective-C Style Guides

If ours doesn‘t fit your tastes, have a look at some other style guides:

时间: 2024-10-07 15:14:03

iOS编码规范的相关文章

iOS编码规范参考

目录 1  注释 1.1  多行注释 1.2  单行注释 1.3  函数的注释 2  命名 2.1  常量的命名 2.2  函数的命名 2.3  变量的命名 2.3.1  成员变量 2.3.2  公共变量命名 2.3.3  实例变量命名 2.4  图片的命名 2.5  类的命名 2.5.1分类名 2.6  条件语句 2.7  变量 3  下划线 4  Immutable 实例初始化 5  类型 5.1  CGRect 函数 5.2  常量 5.3  枚举类型 5.4  布尔变量 5.5  单例

iOS编码规范(简版)

1. 总体指导原则 [规则1-1]首先是为人编写程序,其次才是计算机. 说明:这是软件开发的基本要点,软件的生命周期贯穿产品的开发.测试.生产.用户使用.版本升级和后期维护等长期过程,只有易读.易维护的软件代码才具有生命力,所以提倡写代码之前多思考,特别是逻辑复杂或者技术难点较高的地方,个人思考不清楚的,可以和团队成员进行沟通. [规则1-2]保持代码的简明清晰,避免过分的编程技巧. 说明:简单是最美.保持代码的简单化是软件工程化的基本要求.不要过分追求技巧,否则会降低程序的可读性. [规则1-

iOS编码规范(文档)

文件命名规范: 1. 项目统一使用类前缀ZY. 2. 分类命名+后面统一使用ZYExtension,例:NSDictionary+ZYExtension.h,常用分类定义在内部并写好文档注释.如果功能性分类内部方法较多可以考虑按功能命名. 3. model文件可按服务器接口名或字段名命名,view.viewModel和controller文件可按功能命名. 4. 切图命名:home_menu_chat,->模块_功能_具体名字,切图命名很重要,这点可与美术沟通,让他们直接命名好再给我们,可以大大

iOS:Cocoa编码规范 -[译]Coding Guidelines for Cocoa

--原文地址:https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/FrameworkImpl.html Cocoa编码规范 --前言 用公共API开发一个Cocoa框架,插件,或其他可执行目标,里面的命名编写和规范不同于一般应用程序的开发.因为你开发出来东西是给开发者用的看的,并且他们不熟悉你的编程接口.这个时候API的命名约定就派上用场了,因为它使你的写

iOS 注释的5要3不要和编码规范的26个方面

注释 代码注释,可以说是比代码本身更重要.这里有一些方法可以确保你写在代码中的注释是友好的: 不要重复阅读者已经知道的内容 能明确说明代码是做什么的注释对我们是没有帮助的. // If the color is red, turn it green if (color.is_red()) { color.turn_green(); }   要注释说明推理和历史 如果代码中的业务逻辑以后可能需要更新或更改,那就应该留下注释:) /* The API currently returns an arr

ios之编码规范具体说明

iOS代码规范: 所有代码规范所有遵循苹果sdk的原则,不清楚的请訪问苹果SDK文档或下载官方Demo查看. 1.project部分: 将项目中每一个功能模块相应的源文件放入同一目录下,使用虚拟目录. 引用的.a和相关的文件.独立使用目录存放.并标明是SDK 2.类: 命名:首字母大写,其后每一个单词首字母大写,类文件的名字必须与类中基本的@interface类名字一致.(例:RootViewController.PersonInfo) category和protocol能够放在独立文件里,或放

ios之编码规范详细说明

iOS代码规范: 所有代码规范全部遵循苹果sdk的原则,不清楚的请访问苹果SDK文档或下载官方Demo查看. 1.工程部分: 将项目中每个功能模块对应的源文件放入同一文件夹下,使用虚拟文件夹. 引用的.a和相关的文件,独立使用文件夹存放,并标明是SDK 2.类: 命名:首字母大写,其后每个单词首字母大写,类文件的名字必须与类中主要的@interface类名字一致.(例:RootViewController,PersonInfo) category和protocol可以放在独立文件中,或放在某个类

【分享】[iOS翻译]Cocoa编码规范

http://www.cnblogs.com/yangfaxian/p/4673894.html 简介: 本文整理自Apple文档<Coding Guidelines for Cocoa>.这份文档原意是给Cocoa框架.插件及公共API开发者提供一些编码指导,实质上相当于Apple内部的编码规范.在多人协作时,一份统一的代码规范大大减少开发者之间的沟通成本,极力推荐. 目录: 一.代码命名基础 二.方法 三.函数 四.Property及其他 五.缩写 一.代码命名基础 1.通用原则 1.1 

html编码规范

不久前接到老大下达的任务,要拟定一份公司前端编码规范的草稿,参考了各大公司的编码规范,结合现在公司的特点,整理出以下编码规范: html规范 1 文件相关 (1) 文件名以英文为主,可以使用下划线(如active.html),压缩包以项目名+日期的形式. (2) 统一使用utf-8编码. (3) css.js发布到线上都需要压缩. (4) 在追求高度优化的站点,需要对图片也进行无损压缩. 2 代码风格 2.1 命名 (1) 元素 id 必须保证页面唯一.(解释:同一个页面中,不同的元素包含相同的