SlideShare una empresa de Scribd logo
1 de 33
Google Objective-C
Style Guide
2014/08/29
Winston Hsieh
Outline
 Background
 Example Preview
 Spacing and Formatting
 Naming
 Comments
 Cocoa and Objective-C Features
 Cocoa Pattern
 Historical Notes
 Q&A
2
Background
 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
 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).
 https://code.google.com/p/google-toolbox-for-mac/
 Code meant to be shared across different projects is a good
candidate to be included in this repository.
3
Example Preview (1)
 Blank lines before and after
 @interface
 @implementation
 @end are optional
 If your @interface declares instance variables, a blank line
should come after the closing brace (})
4
Example Preview (2)
 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
 An example source file, demonstrating the correct commenting
and spacing for the @implementation of an interface.
5
Spacing And Formatting (1)
 Spaces vs. Tabs
 We use spaces for indentation.
 Do not use tabs in your code.
 You should set your editor to emit spaces when you hit the tab key.
 Line Length
 The maximum line length for Objective-C and Objective-C++ files is
100 columns.
 Projects may opt to use an 80 column limit for consistency with the
C++ style guide.
 You can make violations easier to spot by enabling
• Preferences > Text Editing > Page guide at column: 100 in Xcode
6
Spacing And Formatting (2)
 Method Declarations and Definitions
 One space should be used between the - or + and the return type
 No spacing in the parameter list except between parameters.
 The spacing before the asterisk is optional.
 If you have too many parameters to fit on one line, giving each its
own line is preferred.
 If multiple lines are used, align each using the colon before the
parameter.
 When the first keyword is shorter than the others, indent the later
lines by at least four spaces, maintaining colon alignment:
7
Spacing And Formatting (3)
 Method Invocations
 Method invocations should be formatted much like method
declarations
 Invocations should have all arguments on one line:
 Or have one argument per line, with colons aligned:
 When the first keyword is shorter than the others, indent the later
lines by at least four spaces, maintaining colon alignment:
 Invocations containing inlined blocks may have their segments left-
aligned at a four space indent.
8
Spacing And Formatting (4)
 @public and @private
 The @public and @private access modifiers should be indented by
1 space.
 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 @catch and the caught object declaration.
9
Spacing And Formatting (5)
 Protocols
 There should not be a space between the type identifier and the
name of the protocol encased in angle brackets.
 Container Literals
 If the collection fits on one line, put a single space after the opening
and before the closing brackets.
 Incorrect example
10
Spacing And Formatting (6)
 If the collection spans more than a single line, place the opening
bracket on the same line as the declaration, indent the body by two
spaces, and place the closing bracket on a new line that is indented
to the same level as the opening bracket.
 For dictionary literals, there should be one space before the colon
and at least one space after it (to optionally align the values).
11
Spacing And Formatting (7)
 Incorrect example
12
Spacing And Formatting (8)
 Blocks
 Code inside blocks should be indented four spaces.
 There are several appropriate style rules, depending on how long
the block is:
• If the block can fit on one line, no wrapping is necessary.
• If it has to wrap, the closing brace should line up with the first character of the
line on which the block is declared.
• Code within the block should be indented four spaces.
• If the block is large, e.g. more than 20 lines, it is recommended to move it out-
of-line into a local variable.
• If the block takes no parameters, there are no spaces between the characters
^{. If the block takes parameters, there is no space between the ^( characters,
but there is one space between the ) { characters.
• Invocations containing inlined blocks may have their segments left-aligned at
a four-space indent. This helps when invocations contain multiple inlined
blocks.
• Two space indents inside blocks are also allowed, but should only be used
when it's consistent with the rest of the project's code.
 Example
• http://google-
styleguide.googlecode.com/svn/trunk/objcguide.xml?showone=Blocks#Blocks
13
Naming (1)
 File Name
 File names should reflect the name of the class implementation that
they contain—including case.
 File extensions should be as follows:
 File names for categories should include the name of the class being
extended
• e.g. GTMNSString+Utils.h or GTMNSTextView+Autocomplete
 Objective-C++
 In order to minimize clashes between the differing naming styles when
mixing Cocoa/Objective-C and C++, follow the style of the method
being implemented.
• If you're in an @implementation block, use the Objective-C naming rules.
• If you're implementing a method for a C++ class, use the C++ naming rules.
 Class Names
 Class names (along with category and protocol names) should start as
uppercase and use mixed case to delimit words.
14
Naming (2)
 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 Name
 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.
• For example: myLocalVariable
 Instance variables have leading underscores.
• For example: _myInstanceVariable
15
Comments (1)
 File Comments
 A file may optionally start with a description of its contents.
 Every file should contain the following items, in order:
• license boilerplate if necessary. Choose the appropriate boilerplate for the
license used by the project (e.g. Apache 2.0, BSD, LGPL, GPL).
• a basic description of the contents of the file if necessary.
 If you make significant changes to a file with an author line,
consider deleting the author line since revision history already
provides a more detailed and accurate record of authorship.
16
Comments (2)
 Declaration Comments
 Every interface, category, and protocol declaration should have an
accompanying comment describing its purpose and how it fits into
the larger picture
 Implementation Comments
 Use vertical bars to quote variable names and symbols in
comments rather than quotes or naming the symbol inline.
 When quoting something which already contains quotes
17
Cocoa and Objective-C Features (1)
 Instance Variables In Headers Should Be @private
 Instance variables should typically be declared in implementation
files or auto-synthesized by properties.
 Identify Designated Initializer
 Comment and clearly identify your designated initializer.
 Override Designated Initializer
 When writing a subclass that requires an init... method, make sure
you override the superclass' designated initializer.
 Overridden NSObject Method Placement
 It is strongly recommended and typical practice to place overridden
methods of NSObject at the top of an @implementation
18
Cocoa and Objective-C Features (2)
 Initialization
 Don't initialize variables to 0 or nil in the init method; it's redundant.
 Avoid +new
 Do not invoke the NSObject class method new, nor override it in a
subclass.
 Instead, use alloc and init methods to instantiate retained objects.
 Keep the Public API Simple
 Keep your class simple; avoid "kitchen-sink" APIs.
• Unlike C++, Objective-C doesn't have a way to differentiate between public
and private methods—everything is public.
• As a result, avoid placing methods in the public API unless they are actually
expected to be used by a consumer of the class.
19
Cocoa and Objective-C Features (3)
 #import and #include
 #import Objective-C/Objective-C++ headers, and #include C/C++
headers.
20
Cocoa and Objective-C Features (4)
 Use Root Frameworks
 Include root frameworks over individual files.
 Prefer To autorelease At Time of Creation
 When creating new temporary objects, autorelease them on the
same line as you create them rather than a separate release later
in the same method.
21
Cocoa and Objective-C Features (5)
 Autorelease Then Retain
 Assignment of objects follows the autorelease then retain pattern.
 Avoid Accessors During init and dealloc
 Instance subclasses may be in an inconsistent state during init and
dealloc method execution, so code in those methods should avoid
invoking accessors.
22
Cocoa and Objective-C Features (6)
 Dealloc Instance Variables in Declaration Order
 dealloc should process instance variables in the same order the
@interface declares them, so it is easier for a reviewer to verify.
 Setters copy NSStrings
 Never just retain the string. This avoids the caller changing it under
you without your knowledge.
23
Cocoa and Objective-C Features (7)
 Avoid Throwing Exceptions
 Don't @throw Objective-C exceptions, but you should be prepared
to catch them from third-party or OS calls.
 nil Checks
 Use nil checks for logic flow only.
 BOOL Pitfalls
 Be careful when converting general integral values to BOOL.
 Avoid comparing directly with YES.
 BOOL is defined as a signed char in Objective-C which means that
it can have values other than YES (1) and NO (0).
 Do not cast or convert general integral values directly to BOOL.
24
Cocoa and Objective-C Features (8)
 Using logical operators (&&, || and !) with BOOL is also valid and
will return values that can be safely converted to BOOL without the
need for a ternary operator.
 Donot directly compare BOOL variables directly with YES.
25
Cocoa and Objective-C Features (9)
 Properties
 Naming
• A property's associated instance variable's name must conform to the leading _
requirement.
• The property's name should be the same as its associated instance variable
without the leading _.
 Location
• A property's declaration must come immediately after the instance variable
block of a class interface.
• A property's definition (if not using automatic synthesis) must come
immediately after the @implementation block in a class definition. They are
indented at the same level as the @interface or @implementation statements
that they are enclosed in.
26
Cocoa and Objective-C Features (10)
 Atomicity
 Be aware of the overhead of properties.
 By default, all synthesized setters and getters are atomic.
 This gives each set and get calls a substantial amount of
synchronization overhead.
 Declare your properties nonatomic unless you require atomicity
 Dot notation
 Dot notation is idiomatic style for Objective-C 2.0.
 It may be used when doing simple operations to get and set a
@property of an object, but should not be used to invoke other
object behavior.
27
Cocoa and Objective-C Features (11)
 Interfaces Without Instance Variables
 Omit the empty set of braces on interfaces that do not declare any
instance variables.
 Automatically Synthesized Instance Variables
 Use of automatically synthesized instance variables is preferred.
28
Cocoa and Objective-C Features (12)
 Automatic Reference Counting (ARC)
 For projects that use Xcode 4.2 or later and will run only on 64-bit
Mac OS X 10.7 and iOS 5.0 and later, ARC is preferred.
 Use manual reference counting when supporting earlier
environments where zeroing weak pointers are not available.
29
Cocoa and Objective-C Features (13)
 NSNumber Literals
 For projects that use Xcode 4.4 or later with clang, the use of
NSNumber literals is allowed.
 Note however that this will limit the portability of your code to other
toolchains.
30
Cocoa Patterns
 Delegate Pattern
 Delegate objects should not be retained when doing so would create a
retain cycle.
 A class that implements the delegate pattern should typically:
• Have an instance variable named _delegate to reference the delegate.
• Thus, the accessor methods should be named delegate and setDelegate.
• The _delegate object should be weak if the class is typically retained by its delegate,
such that a strong delegate would create a retain cycle.
 Model/View/Controller
 Separate model from view: don't build assumptions about the
presentation into the model or data source.
 Keep the interface between the data source and the presentation
abstract.
 Don't give the model knowledge of its view.
 Separate controller from view and model: don't put all of the "business
logic" into view-related classes.
 Make controller classes to host this code, but ensure that the controller
classes don't make too many assumptions about the presentation.
 Define callback APIs with @protocol, using @optional if not all the
methods are required.
31
Historical Notes
 Trailing vs Leading Underscores
 Trailing underscores were once preferred for instance variable
names.
 Our style guide used to have a rule saying that instance variables
should be named with a trailing underscore, similar to the naming of
member variables in C++.
 This was changed to leading underscores to be consistent with the
broader Objective-C community, to better follow Apple's official
guidelines, and to allow for use of new compiler features like
automatic instance variable synthesis.
 New projects are strongly encouraged to use leading underscores.
32
Q&A

Más contenido relacionado

La actualidad más candente (13)

Function pointer - Wikipedia, the free encyclopedia
Function pointer - Wikipedia, the free encyclopediaFunction pointer - Wikipedia, the free encyclopedia
Function pointer - Wikipedia, the free encyclopedia
 
Srgoc dotnet
Srgoc dotnetSrgoc dotnet
Srgoc dotnet
 
Rpg Pointers And User Space
Rpg Pointers And User SpaceRpg Pointers And User Space
Rpg Pointers And User Space
 
Csc153 chapter 01
Csc153 chapter 01Csc153 chapter 01
Csc153 chapter 01
 
BASIC CONCEPTS OF C++ CLASS 12
BASIC CONCEPTS OF C++ CLASS 12BASIC CONCEPTS OF C++ CLASS 12
BASIC CONCEPTS OF C++ CLASS 12
 
Ec oop f90
Ec oop f90Ec oop f90
Ec oop f90
 
Csc153 chapter 07
Csc153 chapter 07Csc153 chapter 07
Csc153 chapter 07
 
New c sharp4_features_part_i
New c sharp4_features_part_iNew c sharp4_features_part_i
New c sharp4_features_part_i
 
Csc253 chapter 09
Csc253 chapter 09Csc253 chapter 09
Csc253 chapter 09
 
Oops
OopsOops
Oops
 
C interview questions
C interview questionsC interview questions
C interview questions
 
Program by Demonstration using Version Space Algebra
Program by Demonstration using Version Space AlgebraProgram by Demonstration using Version Space Algebra
Program by Demonstration using Version Space Algebra
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
 

Similar a Google Objective-C Style Guide

1 Project 2 Introduction - the SeaPort Project seri.docx
1  Project 2 Introduction - the SeaPort Project seri.docx1  Project 2 Introduction - the SeaPort Project seri.docx
1 Project 2 Introduction - the SeaPort Project seri.docx
honey725342
 
1. Coding Conventions [Part 1]
1. Coding Conventions [Part 1]1. Coding Conventions [Part 1]
1. Coding Conventions [Part 1]
Hardik Patel
 
Presentation
PresentationPresentation
Presentation
bugway
 

Similar a Google Objective-C Style Guide (20)

Coding conventions
Coding conventionsCoding conventions
Coding conventions
 
1 Project 2 Introduction - the SeaPort Project seri.docx
1  Project 2 Introduction - the SeaPort Project seri.docx1  Project 2 Introduction - the SeaPort Project seri.docx
1 Project 2 Introduction - the SeaPort Project seri.docx
 
Android coding standard
Android coding standard Android coding standard
Android coding standard
 
Bb Tequila Coding Style (Draft)
Bb Tequila Coding Style (Draft)Bb Tequila Coding Style (Draft)
Bb Tequila Coding Style (Draft)
 
Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Best Coding Practices in Java and C++
Best Coding Practices in Java and C++
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
Dot net interview questions and asnwers
Dot net interview questions and asnwersDot net interview questions and asnwers
Dot net interview questions and asnwers
 
A Program Transformation Technique to Support Aspect-Oriented Programming wit...
A Program Transformation Technique to Support Aspect-Oriented Programming wit...A Program Transformation Technique to Support Aspect-Oriented Programming wit...
A Program Transformation Technique to Support Aspect-Oriented Programming wit...
 
Perfomatix - Android Coding Standards
Perfomatix - Android Coding StandardsPerfomatix - Android Coding Standards
Perfomatix - Android Coding Standards
 
1. Coding Conventions [Part 1]
1. Coding Conventions [Part 1]1. Coding Conventions [Part 1]
1. Coding Conventions [Part 1]
 
GTU Guidelines for Project on JAVA
GTU Guidelines for Project on JAVAGTU Guidelines for Project on JAVA
GTU Guidelines for Project on JAVA
 
Presentation
PresentationPresentation
Presentation
 
Impact of indentation in programming
Impact of indentation in programmingImpact of indentation in programming
Impact of indentation in programming
 
GTU PHP Project Training Guidelines
GTU PHP Project Training GuidelinesGTU PHP Project Training Guidelines
GTU PHP Project Training Guidelines
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
 
Java
JavaJava
Java
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
 
A Program Transformation Technique To Support AOP Within C Template
A Program Transformation Technique To Support AOP Within C   TemplateA Program Transformation Technique To Support AOP Within C   Template
A Program Transformation Technique To Support AOP Within C Template
 
Web technologies-course 07.pptx
Web technologies-course 07.pptxWeb technologies-course 07.pptx
Web technologies-course 07.pptx
 

Último

1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
AldoGarca30
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
chumtiyababu
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 

Último (20)

1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptx
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 

Google Objective-C Style Guide

  • 2. Outline  Background  Example Preview  Spacing and Formatting  Naming  Comments  Cocoa and Objective-C Features  Cocoa Pattern  Historical Notes  Q&A 2
  • 3. Background  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  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).  https://code.google.com/p/google-toolbox-for-mac/  Code meant to be shared across different projects is a good candidate to be included in this repository. 3
  • 4. Example Preview (1)  Blank lines before and after  @interface  @implementation  @end are optional  If your @interface declares instance variables, a blank line should come after the closing brace (}) 4
  • 5. Example Preview (2)  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  An example source file, demonstrating the correct commenting and spacing for the @implementation of an interface. 5
  • 6. Spacing And Formatting (1)  Spaces vs. Tabs  We use spaces for indentation.  Do not use tabs in your code.  You should set your editor to emit spaces when you hit the tab key.  Line Length  The maximum line length for Objective-C and Objective-C++ files is 100 columns.  Projects may opt to use an 80 column limit for consistency with the C++ style guide.  You can make violations easier to spot by enabling • Preferences > Text Editing > Page guide at column: 100 in Xcode 6
  • 7. Spacing And Formatting (2)  Method Declarations and Definitions  One space should be used between the - or + and the return type  No spacing in the parameter list except between parameters.  The spacing before the asterisk is optional.  If you have too many parameters to fit on one line, giving each its own line is preferred.  If multiple lines are used, align each using the colon before the parameter.  When the first keyword is shorter than the others, indent the later lines by at least four spaces, maintaining colon alignment: 7
  • 8. Spacing And Formatting (3)  Method Invocations  Method invocations should be formatted much like method declarations  Invocations should have all arguments on one line:  Or have one argument per line, with colons aligned:  When the first keyword is shorter than the others, indent the later lines by at least four spaces, maintaining colon alignment:  Invocations containing inlined blocks may have their segments left- aligned at a four space indent. 8
  • 9. Spacing And Formatting (4)  @public and @private  The @public and @private access modifiers should be indented by 1 space.  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 @catch and the caught object declaration. 9
  • 10. Spacing And Formatting (5)  Protocols  There should not be a space between the type identifier and the name of the protocol encased in angle brackets.  Container Literals  If the collection fits on one line, put a single space after the opening and before the closing brackets.  Incorrect example 10
  • 11. Spacing And Formatting (6)  If the collection spans more than a single line, place the opening bracket on the same line as the declaration, indent the body by two spaces, and place the closing bracket on a new line that is indented to the same level as the opening bracket.  For dictionary literals, there should be one space before the colon and at least one space after it (to optionally align the values). 11
  • 12. Spacing And Formatting (7)  Incorrect example 12
  • 13. Spacing And Formatting (8)  Blocks  Code inside blocks should be indented four spaces.  There are several appropriate style rules, depending on how long the block is: • If the block can fit on one line, no wrapping is necessary. • If it has to wrap, the closing brace should line up with the first character of the line on which the block is declared. • Code within the block should be indented four spaces. • If the block is large, e.g. more than 20 lines, it is recommended to move it out- of-line into a local variable. • If the block takes no parameters, there are no spaces between the characters ^{. If the block takes parameters, there is no space between the ^( characters, but there is one space between the ) { characters. • Invocations containing inlined blocks may have their segments left-aligned at a four-space indent. This helps when invocations contain multiple inlined blocks. • Two space indents inside blocks are also allowed, but should only be used when it's consistent with the rest of the project's code.  Example • http://google- styleguide.googlecode.com/svn/trunk/objcguide.xml?showone=Blocks#Blocks 13
  • 14. Naming (1)  File Name  File names should reflect the name of the class implementation that they contain—including case.  File extensions should be as follows:  File names for categories should include the name of the class being extended • e.g. GTMNSString+Utils.h or GTMNSTextView+Autocomplete  Objective-C++  In order to minimize clashes between the differing naming styles when mixing Cocoa/Objective-C and C++, follow the style of the method being implemented. • If you're in an @implementation block, use the Objective-C naming rules. • If you're implementing a method for a C++ class, use the C++ naming rules.  Class Names  Class names (along with category and protocol names) should start as uppercase and use mixed case to delimit words. 14
  • 15. Naming (2)  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 Name  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. • For example: myLocalVariable  Instance variables have leading underscores. • For example: _myInstanceVariable 15
  • 16. Comments (1)  File Comments  A file may optionally start with a description of its contents.  Every file should contain the following items, in order: • license boilerplate if necessary. Choose the appropriate boilerplate for the license used by the project (e.g. Apache 2.0, BSD, LGPL, GPL). • a basic description of the contents of the file if necessary.  If you make significant changes to a file with an author line, consider deleting the author line since revision history already provides a more detailed and accurate record of authorship. 16
  • 17. Comments (2)  Declaration Comments  Every interface, category, and protocol declaration should have an accompanying comment describing its purpose and how it fits into the larger picture  Implementation Comments  Use vertical bars to quote variable names and symbols in comments rather than quotes or naming the symbol inline.  When quoting something which already contains quotes 17
  • 18. Cocoa and Objective-C Features (1)  Instance Variables In Headers Should Be @private  Instance variables should typically be declared in implementation files or auto-synthesized by properties.  Identify Designated Initializer  Comment and clearly identify your designated initializer.  Override Designated Initializer  When writing a subclass that requires an init... method, make sure you override the superclass' designated initializer.  Overridden NSObject Method Placement  It is strongly recommended and typical practice to place overridden methods of NSObject at the top of an @implementation 18
  • 19. Cocoa and Objective-C Features (2)  Initialization  Don't initialize variables to 0 or nil in the init method; it's redundant.  Avoid +new  Do not invoke the NSObject class method new, nor override it in a subclass.  Instead, use alloc and init methods to instantiate retained objects.  Keep the Public API Simple  Keep your class simple; avoid "kitchen-sink" APIs. • Unlike C++, Objective-C doesn't have a way to differentiate between public and private methods—everything is public. • As a result, avoid placing methods in the public API unless they are actually expected to be used by a consumer of the class. 19
  • 20. Cocoa and Objective-C Features (3)  #import and #include  #import Objective-C/Objective-C++ headers, and #include C/C++ headers. 20
  • 21. Cocoa and Objective-C Features (4)  Use Root Frameworks  Include root frameworks over individual files.  Prefer To autorelease At Time of Creation  When creating new temporary objects, autorelease them on the same line as you create them rather than a separate release later in the same method. 21
  • 22. Cocoa and Objective-C Features (5)  Autorelease Then Retain  Assignment of objects follows the autorelease then retain pattern.  Avoid Accessors During init and dealloc  Instance subclasses may be in an inconsistent state during init and dealloc method execution, so code in those methods should avoid invoking accessors. 22
  • 23. Cocoa and Objective-C Features (6)  Dealloc Instance Variables in Declaration Order  dealloc should process instance variables in the same order the @interface declares them, so it is easier for a reviewer to verify.  Setters copy NSStrings  Never just retain the string. This avoids the caller changing it under you without your knowledge. 23
  • 24. Cocoa and Objective-C Features (7)  Avoid Throwing Exceptions  Don't @throw Objective-C exceptions, but you should be prepared to catch them from third-party or OS calls.  nil Checks  Use nil checks for logic flow only.  BOOL Pitfalls  Be careful when converting general integral values to BOOL.  Avoid comparing directly with YES.  BOOL is defined as a signed char in Objective-C which means that it can have values other than YES (1) and NO (0).  Do not cast or convert general integral values directly to BOOL. 24
  • 25. Cocoa and Objective-C Features (8)  Using logical operators (&&, || and !) with BOOL is also valid and will return values that can be safely converted to BOOL without the need for a ternary operator.  Donot directly compare BOOL variables directly with YES. 25
  • 26. Cocoa and Objective-C Features (9)  Properties  Naming • A property's associated instance variable's name must conform to the leading _ requirement. • The property's name should be the same as its associated instance variable without the leading _.  Location • A property's declaration must come immediately after the instance variable block of a class interface. • A property's definition (if not using automatic synthesis) must come immediately after the @implementation block in a class definition. They are indented at the same level as the @interface or @implementation statements that they are enclosed in. 26
  • 27. Cocoa and Objective-C Features (10)  Atomicity  Be aware of the overhead of properties.  By default, all synthesized setters and getters are atomic.  This gives each set and get calls a substantial amount of synchronization overhead.  Declare your properties nonatomic unless you require atomicity  Dot notation  Dot notation is idiomatic style for Objective-C 2.0.  It may be used when doing simple operations to get and set a @property of an object, but should not be used to invoke other object behavior. 27
  • 28. Cocoa and Objective-C Features (11)  Interfaces Without Instance Variables  Omit the empty set of braces on interfaces that do not declare any instance variables.  Automatically Synthesized Instance Variables  Use of automatically synthesized instance variables is preferred. 28
  • 29. Cocoa and Objective-C Features (12)  Automatic Reference Counting (ARC)  For projects that use Xcode 4.2 or later and will run only on 64-bit Mac OS X 10.7 and iOS 5.0 and later, ARC is preferred.  Use manual reference counting when supporting earlier environments where zeroing weak pointers are not available. 29
  • 30. Cocoa and Objective-C Features (13)  NSNumber Literals  For projects that use Xcode 4.4 or later with clang, the use of NSNumber literals is allowed.  Note however that this will limit the portability of your code to other toolchains. 30
  • 31. Cocoa Patterns  Delegate Pattern  Delegate objects should not be retained when doing so would create a retain cycle.  A class that implements the delegate pattern should typically: • Have an instance variable named _delegate to reference the delegate. • Thus, the accessor methods should be named delegate and setDelegate. • The _delegate object should be weak if the class is typically retained by its delegate, such that a strong delegate would create a retain cycle.  Model/View/Controller  Separate model from view: don't build assumptions about the presentation into the model or data source.  Keep the interface between the data source and the presentation abstract.  Don't give the model knowledge of its view.  Separate controller from view and model: don't put all of the "business logic" into view-related classes.  Make controller classes to host this code, but ensure that the controller classes don't make too many assumptions about the presentation.  Define callback APIs with @protocol, using @optional if not all the methods are required. 31
  • 32. Historical Notes  Trailing vs Leading Underscores  Trailing underscores were once preferred for instance variable names.  Our style guide used to have a rule saying that instance variables should be named with a trailing underscore, similar to the naming of member variables in C++.  This was changed to leading underscores to be consistent with the broader Objective-C community, to better follow Apple's official guidelines, and to allow for use of new compiler features like automatic instance variable synthesis.  New projects are strongly encouraged to use leading underscores. 32
  • 33. Q&A

Notas del editor

  1. 1