Notes
Hide details in this Guide
This style guide contains a lot of initial invisible details. They are marked as triangle icons, which you can see on the left. Click it now and you will see "Long live" below.
Background
Objective-C is a dynamic and object-oriented C Language extension. It is designed to be easy to use and read, and supports complex object-oriented design. It is the main language for developing new applications on Mac OS X and iPhone.
Cocoa is a major application framework on Mac OS X. This is an Objective-C class set for fast development of full-featured Mac OS X applications.
Apple has compiled a good and widely accepted coding guide for Objective-C, and Google has written a similar guide for C ++. This Objective-C Guide is intended to be a natural combination of general recommendations for Apple and Google. Therefore, before reading this Guide, make sure you have spent the following:
Apple Cocoa coding Guide
Google's open-source C ++ Design Guide
Note: The same applies to all objects that are disabled in the Google C ++ guide, unless otherwise specified in this Article.
This document describes the Objective-C (and Objective-C ++) coding guidelines and practices used in all Mac OS X code. Many of these guidelines have evolved and become obsolete in other projects and teams. Open-source projects developed by Google comply with the requirements in this Guide.
Google has released open-source code that complies with these guidelines as part of the Google Toolkit (GTM) for Mac projects. This means that the code to be shared in different projects is a good candidate for inclusion in this library.
Note: This guide is not an Objective-C tutorial. We assume that the reader is familiar with such a language. If you are a beginner or need to review Objective-C, read the Objective-C programming language book.
Example
They say that an example is better than a thousand words. Let's start to use an example to let you feel the style, spacing, and naming of Objective-C.
An example of a header file shows the correct comments and spacing declared by @ interface:
01 # import <Foundation/Foundation. h>
02
03 // A sample class demonstrating good Objective-C style. All interfaces,
04 // categories, and protocols (read: all top-level declarations in a header)
05 // MUST be commented. Comments must also be adjacent to the object they're
06 // documenting.
07 //
08 // (no blank line between this comment and the interface)
09 @ interface Foo: NSObject {
10 @ private
11 NSString * _ bar;
12 NSString * _ bam;
13}
14
15 // Returns an autoreleased instance of Foo. See-initWithBar: for details
16 // about | bar |.
17 + (id) fooWithBar :( NSString *) bar;
18
19 // Designated initializer. | bar | is a thing that represents a thing that
20 // does a thing.
21-(id) initWithBar :( NSString *) bar;
22
23 // Gets and sets | _ bar |.
24-(NSString *) bar;
25-(void) setBar :( NSString *) bar;
26
27 // Does some work with | blah | and returns YES if the work was completed
28 // successfully, and NO otherwise.
29-(BOOL) doWorkWithBlah :( NSString *) blah;
30
31 @ end
An example of a source file shows the correct comments and spacing of @ implementation of an interface. It also contains some important methods, such as getters, setters, init, and dealloc reference implementation: 01 # import "Foo. h"
02
03
04 @ implementation Foo
05
06 + (id) fooWithBar :( NSString *) bar {
07 return [[[self alloc] initWithBar: bar] autorelease];
08}
09
10 // Must always override super's designated initializer.
11-(id) init {
12 return [self initWithBar: nil];
13}
14
15-(id) initWithBar :( NSString *) bar {
16 if (self = [super init]) {
17 _ bar = [bar copy];
18 _ bam = [[NSString alloc] initWithFormat: @ "hi % d", 3];
19}
20 return self;
21}
22
23-(void) dealloc {
24 [_ bar release];
25 [_ bam release];
26 [super dealloc];
27}
28
29-(NSString *) bar {
30 return _ bar;
31}
32
33-(void) setBar :( NSString *) bar {
34 [_ bar autorelease];
35 _ bar = [bar copy];
36}
37
38-(BOOL) doWorkWithBlah :( NSString *) blah {
39 //...
40 return NO;
41}
42
43 @ end
Empty rows before and after @ interface, @ implementation, and @ end are optional. If your @ interface declares the real parameter, a blank line is required after the right brackets.
Unless the interface or implementation is short, for example, adding a blank line is usually readable when defining a small part of the private method or a bridge class.
Spacing and format
Space and tab)
▶
Only space is used, and two spaces are indented at a time.
Width of each line
▶
You should try to keep each line within 80 characters in your code.
Method description and definition
▶
There must be a space between-(or +) and the return value type. In the parameter list, there must be no spacing between parameters.
Method call
▶
The format of the method call must be consistent with the defined format. When multiple formatting styles are available, follow the Convention to use the method used in the given source file.
@ Public and @ private
▶
@ Public and @ private access modifiers must be followed by a space.
Exceptions
▶
When a single row is created, use the @ tag to format the conditions. Add a space between the @ tag and the open brackets ({), and the @ catch and object capture declarations are the same.
Protocols
▶
There should be no space between the type identifier and the Protocols name encapsulated in angle brackets.
Blocks
▶
Blocks prefers the target selector mode when creating callback functions, which makes the code easier to read. The code in the block should be indented by four spaces.
Name
Naming rules are very important for code maintainability. Objective-C naming tends to be too long, but it brings a good sense of code reading, just like reading prose, while avoiding a lot of unnecessary comments.
When writing pure Objective-C code, we primarily follow standard Objective-C naming rules. These naming rules may be far from the naming rules of C ++. For example, in Google's C ++ specification, underscores (_) are recommended between words in variable names, while in Objective-C, the camper naming method is recommended, this is also a standard practice in the Objective-C community.
The acronyms of any class, directory, method, or variable should be set to uppercase. The following are the acronyms of the uppercase letters used by Apple: URL, TIFF, and EXIF.
However, when writing Objective-C ++ code, it is often not in full compliance with the specifications. Many projects use Objective-C, Cocoa, or C ++ frontend communication with native Cocoa to implement cross-platform C ++ APIs. This leads to a direct conflict between the two language specifications.
The solution is to determine the name based on the method/function implementation method. If you are in a @ implementationblock, use the Objective-C naming convention. If you implement a method in a C ++ class, use the C ++ naming convention. This avoids the mixed use of instance variables and naming rules of local variables in a function, and greatly reduces the readability of the Code.
File Name
▶
The file name should reflect the name of the class implementation contained in it, which is case-sensitive according to the conventions in your project.
Objective-C ++
▶
In a source code file, Objective-C ++ follows the style of your implemented functions/methods.
Class Name
▶
The class name (category and protocol name) should be in uppercase and begin to use case-sensitive mixture to distinguish words.
Category name
▶
The category name should start with a prefix of 2 to 3 letters to identify whether the category is part of the project or open for use. Category. The name should be combined with the name of the extended class.
Objective-C method name
▶
The method name must start with a lower-case letter, and contain both uppercase and lowercase letters. Each name parameter should also start with a lowercase letter.
Variable name
▶
Variable names start with lowercase letters and are case-sensitive. The instance variable starts with an underscore. For example, myLocalVariable, _ myInstanceVariable.
Note
Despite the pain points of writing, they are absolutely crucial to keep your code readable. The following rules describe when and where you should add comments. But remember that although annotations are important, the best code is self-Annotated. It is much better to give a meaningful name to a variable and type than to use an obscure name and then use annotations to explain it.
Write comments to your readers: The next contributor to read your code. Write more. You may be yourself next time!
Remember that the rules and agreements listed in all c ++ programming specifications also take effect here. The following are some supplements.
File Comments
▶
You can choose to write a description of the content at the beginning of a file.
Declaration Comments
▶
Each interface, category, and Protocol declaration should have an accompanying Comment to describe its role and how it fits into the overall environment.
Implement Declaration Implementation Comments
▶
Use vertical arrangement to reference variable names and symbols in comments. Do not write them into a whole line.
Object Ownership
▶
When the pointer ownership model exceeds the common Objective-C usage, the more detailed the description is, the better.
Features of Cocoa and Objective-C
Variables declared in the header file must be private
When the variable is declared in the header file, the variable must be marked as @ private
Identifiers
Describe or identify the initialization Device
Override Initiator
When you write a subclass containing the init () method, make sure that the initialization of the parent class is overwritten.
Position of NSObject method Rewriting
We recommend that you place the NSObject rewrite method on the annotation of @ implementation.
Initialization
Do not initialize the variable to 0 or nil in the init method.
Avoid handling new methods
Do not try to call the new () method of the NSObject class or rewrite this method in its subclass. We can use its init method to instantiate these reserved objects.
Keep public APIs simple
Keep your class as simple as possible: avoid over-rendering APIs. If some methods do not need to be made public, do not disclose them. Use private to avoid clutter of Public headers.
# Import and # include
# Import is used when the Objective-C/Object-C ++ header file is introduced; # include is used when the C/C ++ header file is introduced.
Exploitation and framework
It should include the framework and
After creation, the release can be destroyed.
When creating some temporary objects, it is better to destroy and release the created row than to create and destroy it in the same method later.
Release and retain
The business of the object follows the release and keep rules
Avoid accessors when executing the init or dealloc Method
When the init and dealloc methods are being executed, the subclass instantiation may be in an unstable state. Therefore, the code in these methods should avoid calling other accessors.
Dealloc instance variable in declared order
▶
Dealloc instance variables should be performed in the same order as the @ interface declaration. This makes it easy for reviewers to verify.
Setters copy NSStrings
▶
Setters uses an NSString and should always copy the string it accepts.
Avoid throwing exceptions
▶
Do not @ throw Objective-C exception, but you should be prepared to capture them from a third party or system call.
Nil check
▶
Only use nil check for the logical flow.
BOOL trap
▶
When converting a common integer value to a BOOL type, be careful not to directly compare it with YES.
Attribute
▶Note that the direct use of @ property annotation is allowed in the following cases: the attribute will limit your code to be allowed on iPhone and Mac OS X 10.5 (snow leopard) the Objective-C 2.0 features of the above versions. The dot symbol can be accessed only when @ property is declared.
No interface for sample Variables
▶Do not declare any instance variables except empty braces.
Automatically synthesize instance variables
▶Automatic merging of instance variables is allowed. The compiled code must support earlier compilation tool chain versions (Xcode 4.3 or earlier or GCC compilation) or directly use the @ synthesize annotation to call the properties inherited from the protocol.
Automatic Reference count (ARC)
▶Because the project uses Xcode 4.2 or later and will only run in 64-bit Mac OS X 10.7 and iOS 5.0 and later versions, ARC is preferred. Manual reference counting is unavailable when zero weak pointers are supported in earlier environments.
The class that requires ARC should contain a preprocessing command to prevent compilation from using manual reference counting.
The ownership delimiters of _ unsafe _ unretained and _ weak should be prior to the variable name. You do not need to specify _ strong for the variable because it is the default value. On the other hand, the attribute should always specify the strong keyword rather than the default value of the compiler.
The prepared files require preprocessing commands when using the ARC to prevent compilation without the ARC. See the code snippets below for details.
NSNumber Literal Value
▶For C language projects created using Xcode4.4 or a later version, using NSNumber is allowed. However, using this method will restrict the portability of your code to other tool chains.
Cocoa Mode
Delegation Mode
▶Delegate objects should not be retained.
Model, view, Controller
▶Detach a model from a view. Separates controllers from views and models. Use the @ protocols annotation to call back APIs.
History description
Suffix underline vs prefix underline
▶The suffix underline is used to indicate the name of the sample variable.