Google 的 Objective-C 代码规范指南 已翻译 100%

oschina 投递于 2013/05/15 09:52 (共 16 段, 翻译完成于 05-21)
阅读 13174
收藏 112
11
加载中

Important Note

Displaying Hidden Details in this Guide

This style guide contains many details that are initially hidden from view. They are marked by the triangle icon, which you see here on your left. Click it now. You should see "Hooray" appear below.

Background

Objective-C is a very dynamic, object-oriented extension of C. It's designed to be easy to use and read, while enabling sophisticated object-oriented design. It is the primary development language for new applications on Mac OS X and the iPhone.

Cocoa is one of the main application frameworks on Mac OS X. It is a collection of Objective-C classes that provide for rapid development of full-featured Mac OS X applications.

已有 1 人翻译此段
我来翻译

Apple has already written a very good, and widely accepted, coding guide for Objective-C. Google has also written a similar guide for C++. This Objective-C guide aims to be a very natural combination of Apple's and Google's general recommendations. So, before reading this guide, please make sure you've read:

Note that all things that are banned in Google's C++ guide are also banned in Objective-C++, unless explicitly noted in this document.

已有 1 人翻译此段
我来翻译

The purpose of this document is to describe the Objective-C (and Objective-C++) coding guidelines and practices that should be used for all Mac OS X code. Many of these guidelines have evolved and been proven over time on other projects and teams. Open-source projects developed by Google conform to the requirements in this guide.

Google has already released open-source code that conforms to these guidelines as part of the Google Toolbox for Mac project (abbreviated GTM throughout this document). Code meant to be shared across different projects is a good candidate to be included in this repository.

Note that this guide is not an Objective-C tutorial. We assume that the reader is familiar with the language. If you are new to Objective-C or need a refresher, please read The Objective-C Programming Language .

已有 1 人翻译此段
我来翻译

Example

They say an example is worth a thousand words so let's start off with an example that should give you a feel for the style, spacing, naming, etc.

An example header file, demonstrating the correct commenting and spacing for an@interfacedeclaration

#import <Foundation/Foundation.h>

// A sample class demonstrating good Objective-C style. All interfaces,
// categories, and protocols (read: all top-level declarations in a header)
// MUST be commented. Comments must also be adjacent to the object they're
// documenting.
//
// (no blank line between this comment and the interface)
@interface Foo : NSObject {
 @private
  NSString *_bar;
  NSString *_bam;
}

// Returns an autoreleased instance of Foo. See -initWithBar: for details
// about |bar|.
+ (id)fooWithBar:(NSString *)bar;

// Designated initializer. |bar| is a thing that represents a thing that
// does a thing.
- (id)initWithBar:(NSString *)bar;

// Gets and sets |_bar|.
- (NSString *)bar;
- (void)setBar:(NSString *)bar;

// Does some work with |blah| and returns YES if the work was completed
// successfully, and NO otherwise.
- (BOOL)doWorkWithBlah:(NSString *)blah;

@end

An example source file, demonstrating the correct commenting and spacing for the@implementationof an interface. It also includes the reference implementations for important methods like getters and setters,init, anddealloc.

#import "Foo.h"


@implementation Foo

+ (id)fooWithBar:(NSString *)bar {
  return [[[self alloc] initWithBar:bar] autorelease];
}

// Must always override super's designated initializer.
- (id)init {
  return [self initWithBar:nil];
}

- (id)initWithBar:(NSString *)bar {
  if ((self = [super init])) {
    _bar = [bar copy];
    _bam = [[NSString alloc] initWithFormat:@"hi %d", 3];
  }
  return self;
}

- (void)dealloc {
  [_bar release];
  [_bam release];
  [super dealloc];
}

- (NSString *)bar {
  return _bar;
}

- (void)setBar:(NSString *)bar {
  [_bar autorelease];
  _bar = [bar copy];
}

- (BOOL)doWorkWithBlah:(NSString *)blah {
  // ...
  return NO;
}

@end

Blank lines before and after@interface,@implementation, and@endare optional. If your@interfacedeclares instance variables, a blank line should come after the closing brace (}).

Unless an interface or implementation is very short, such as when declaring a handful of private methods or a bridge class, adding blank lines usually helps readability.
已有 1 人翻译此段
我来翻译

Spacing And Formatting

Spaces vs. Tabs

Use only spaces, and indent 2 spaces at a time.

Line Length

Each line of text in your code should try to be at most 80 characters long.

Method Declarations and Definitions

One space should be used between the-or+and the return type, and no spacing in the parameter list except between parameters.

Method Invocations

Method invocations should be formatted much like method declarations. When there's a choice of formatting styles, follow the convention already used in a given source file.

@public and @private

The@publicand@privateaccess modifiers should be indented by 1 space.
已有 1 人翻译此段
我来翻译

Exceptions

Format exceptions with each@label on its own line and a space between the@label and the opening brace ({), as well as between the@catchand the caught object declaration.

Protocols

There should not be a space between the type identifier and the name of the protocol encased in angle brackets.

Blocks

Blocks are preferred to the target-selector pattern when creating callbacks, as it makes code easier to read. Code inside blocks should be indented four spaces.
已有 1 人翻译此段
我来翻译

Naming

Naming rules are very important in maintainable code. Objective-C method names tend to be very long, but this has the benefit that a block of code can almost read like prose, thus rendering many comments unnecessary.

When writing pure Objective-C code, we mostly follow standard Objective-C naming rules. These naming guidelines may differ significantly from those outlined in the C++ style guide. For example, Google's C++ style guide recommends the use of underscores between words in variable names, whereas this guide recommends the use of intercaps, which is standard in the Objective-C community.

Any class, category, method, or variable name may use all capitals for initialisms within the name. This follows Apple's standard of using all capitals within a name for initialisms such as URL, TIFF, and EXIF.

已有 1 人翻译此段
我来翻译

When writing Objective-C++, however, things are not so cut and dry. Many projects need to implement cross-platform C++ APIs with some Objective-C or Cocoa, or bridge between a C++ back-end and a native Cocoa front-end. This leads to situations where the two guides are directly at odds.

Our solution is that the style follows that of the method/function being implemented. If you're in an@implementationblock, use the Objective-C naming rules. If you're implementing a method for a C++class, use the C++ naming rules. This avoids the situation where instance variable and local variable naming rules are mixed within a single function, which would be a serious detriment to readability.

已有 1 人翻译此段
我来翻译

File Names

File names should reflect the name of the class implementation that they contain—including case. Follow the convention that your project uses.

Objective-C++

Within a source file, Objective-C++ follows the style of the function/method you're implementing.

Class Names

Class names (along with category and protocol names) should start as uppercase and use mixed case to delimit words.

Category Names

Category names should start with a 2 or 3 character prefix identifying the category as part of a project or open for general use. The category name should incorporate the name of the class it's extending.

Objective-C Method Names

Method names should start as lowercase and then use mixed case. Each named parameter should also start as lowercase.

Variable Names

Variables names start with a lowercase and use mixed case to delimit words. Instance variables have leading underscores. For example:myLocalVariable,_myInstanceVariable.
已有 1 人翻译此段
我来翻译

Comments

Though a pain to write, they are absolutely vital to keeping our code readable. The following rules describe what you should comment and where. But remember: while comments are very important, the best code is self-documenting. Giving sensible names to types and variables is much better than using obscure names and then trying to explain them through comments.

When writing your comments, write for your audience: the next contributor who will need to understand your code. Be generous—the next one may be you!

Remember that all of the rules and conventions listed in the C++ Style Guide are in effect here, with a few additional points, below.

已有 1 人翻译此段
我来翻译
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接。
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
加载中

评论(8)

JacarriChan
JacarriChan
╮(╯▽╰)╭
MikeManilone
MikeManilone
ObjC 實在是 醜!
shikeaiDev
shikeaiDev
是Apple成就了ObjectC,否则么人用。
Eric_HSBC
Eric_HSBC
能重新整理一下吗?
Duziee
Duziee

引用来自“红薯”的评论

这篇文章排版比较乱,大家将就看吧,原文如此

还有错别字。
东风雨
东风雨
先收着, 以后需要时看看.
麦地兜兜
麦地兜兜
我觉得把这个符号▶去掉就应该不会太乱了,这个太花眼了.
红薯
红薯
这篇文章排版比较乱,大家将就看吧,原文如此
返回顶部
顶部