2
<?xml-stylesheet type="text/xsl" href="styleguide.xsl"?>
3
<GUIDE title="Google Objective-C Style Guide">
22
<CATEGORY title="Important Note">
23
<STYLEPOINT title="Displaying Hidden Details in this Guide">
25
This style guide contains many details that are initially
26
hidden from view. They are marked by the triangle icon, which you
27
see here on your left. Click it now.
28
You should see "Hooray" appear below.
32
Hooray! Now you know you can expand points to get more
33
details. Alternatively, there's an "expand all" at the
40
<CATEGORY title="Background">
43
Objective-C is a very dynamic, object-oriented extension of C. It's
44
designed to be easy to use and read, while enabling sophisticated
45
object-oriented design. It is the primary development language for new
46
applications on Mac OS X and the iPhone.
50
Cocoa is one of the main application frameworks on Mac OS X. It is a
51
collection of Objective-C classes that provide for rapid development of
52
full-featured Mac OS X applications.
56
Apple has already written a very good, and widely accepted, coding guide
57
for Objective-C. Google has also written a similar guide for C++. This
58
Objective-C guide aims to be a very natural combination of Apple's and
59
Google's general recommendations. So, before reading this guide, please make
63
<a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/index.html">
64
Apple's Cocoa Coding Guidelines
70
<a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml">
71
Google's Open Source C++ Style Guide
81
<em>Note that all things that are banned in Google's C++ guide are also
82
banned in Objective-C++, unless explicitly noted in this document.</em>
86
The purpose of this document is to describe the Objective-C (and
87
Objective-C++) coding guidelines and practices that should be used for all
88
Mac OS X code. Many of these guidelines have evolved and been proven over
89
time on other projects and teams.
91
Open-source projects developed by Google
92
conform to the requirements in this guide.
96
Google has already released open-source code that conforms to these
97
guidelines as part of the
98
<a href="http://code.google.com/p/google-toolbox-for-mac/">
99
Google Toolbox for Mac project
101
(abbreviated GTM throughout this document).
102
Code meant to be shared across different projects is a good candidate to
103
be included in this repository.
109
Note that this guide is not an Objective-C tutorial. We assume that the
110
reader is familiar with the language. If you are new to Objective-C or
111
need a refresher, please read
112
<a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/index.html">
113
The Objective-C Programming Language
119
<CATEGORY title="Example">
122
They say an example is worth a thousand words so let's start off with an
123
example that should give you a feel for the style, spacing, naming, etc.
127
An example header file, demonstrating the correct commenting and spacing
128
for an <code>@interface</code> declaration
135
// Created by Greg Miller on 6/13/08.
136
// Copyright 2008 Google, Inc. All rights reserved.
139
#import <Foundation/Foundation.h>
141
// A sample class demonstrating good Objective-C style. All interfaces,
142
// categories, and protocols (read: all top-level declarations in a header)
143
// MUST be commented. Comments must also be adjacent to the object they're
146
// (no blank line between this comment and the interface)
147
@interface GTMFoo : NSObject {
153
// Returns an autoreleased instance of GMFoo. See -initWithString: for details
154
// about the argument.
155
+ (id)fooWithString:(NSString *)string;
157
// Designated initializer. |string| will be copied and assigned to |foo_|.
158
- (id)initWithString:(NSString *)string;
160
// Gets and sets the string for |foo_|.
162
- (void)setFoo:(NSString *)newFoo;
164
// Does some work on |blah| and returns YES if the work was completed
165
// successfuly, and NO otherwise.
166
- (BOOL)doWorkWithString:(NSString *)blah;
172
An example source file, demonstating the correct commenting and spacing
173
for the <code>@implementation</code> of an interface. It also includes the
174
reference implementations for important methods like getters and setters,
175
<code>init</code>, and <code>dealloc</code>.
183
// Created by Greg Miller on 6/13/08.
184
// Copyright 2008 Google, Inc. All rights reserved.
190
@implementation GTMFoo
192
+ (id)fooWithString:(NSString *)string {
193
return [[[self alloc] initWithString:string] autorelease];
196
// Must always override super's designated initializer.
198
return [self initWithString:nil];
201
- (id)initWithString:(NSString *)string {
202
if ((self = [super init])) {
203
foo_ = [string copy];
204
bar_ = [[NSString alloc] initWithFormat:@"hi %d", 3];
219
- (void)setFoo:(NSString *)newFoo {
221
foo_ = [newFoo copy];
224
- (BOOL)doWorkWithString:(NSString *)blah {
234
<CATEGORY title="Spacing And Formatting">
236
<STYLEPOINT title="Spaces vs. Tabs">
238
Use only spaces, and indent 2 spaces at a time.
242
We use spaces for indentation. Do not use tabs in your code.
243
You should set your editor to emit spaces when you hit the tab
249
<STYLEPOINT title="Line Length">
251
Each line of text in your code should be at most 80 characters long.
255
Even though Objective-C tends to be a more verbose language than C++,
256
to aid in the interoperability with that guide, we have decided
257
to keep the limit at 80 columns as well. It's easier to live with
258
than you might expect.
262
We recognize that this rule is controversial, but so much existing
263
code already adheres to it, and we feel that consistency is
267
You can make violations easier to spot in Xcode by going to <i>Xcode
268
> Preferences > Text Editing > Show page guide</i>.
273
<STYLEPOINT title="Method Declarations and Definitions">
275
One space should be used between the <code>-</code> or <code>+</code>
276
and the return type, and no spacing in the parameter list except between
281
Methods should look like this:
284
- (void)doSomethingWithString:(NSString *)theString {
289
The spacing before the asterisk is optional. When adding new code,
290
be consistent with the surrounding file's style.
293
If you have too many parameters to fit on one line, giving each its
294
own line is preferred. If multiple lines are used, align each using
295
the colon before the parameter.
298
- (void)doSomethingWith:(GTMFoo *)theFoo
300
interval:(float)theInterval {
305
When the first keyword is shorter than the others, indent the later
306
lines by at least four spaces. You can do this by making keywords
307
line up vertically, not aligning colons:
310
- (void)short:(GTMFoo *)theFoo
311
longKeyword:(NSRect)theRect
312
evenLongerKeyword:(float)theInterval {
319
<STYLEPOINT title="Method Invocations">
321
Method invocations should be formatted much like method declarations.
322
When there's a choice of formatting styles, follow the convention
323
already used in a given source file.
327
Invocations should have all arguments on one line:
330
[myObject doFooWith:arg1 name:arg2 error:arg3];
333
or have one argument per line, with colons aligned:
336
[myObject doFooWith:arg1
341
Don't use any of these styles:
344
[myObject doFooWith:arg1 name:arg2 // some lines with >1 arg
347
[myObject doFooWith:arg1
348
name:arg2 error:arg3];
350
[myObject doFooWith:arg1
351
name:arg2 // aligning keywords instead of colons
356
As with declarations and definitions, when the keyword lengths make
357
it impossible to align colons and still have four leading
358
spaces, indent later lines by four spaces and align keywords after the
359
first one, instead of aligning the colons.
364
evenLongerKeyword:arg3];
369
<STYLEPOINT title="@public and @private">
371
The <code>@public</code> and <code>@private</code> access modifiers
372
should be indented by 1 space.
376
This is similar to <code>public</code>, <code>private</code>, and
377
<code>protected</code> in C++.
380
@interface MyClass : NSObject {
391
<STYLEPOINT title="Exceptions">
393
Format exceptions with each <code>@</code> label on its own line and a
394
space between the <code>@</code> label and the opening brace
395
(<code>{</code>), as well as between the <code>@catch</code> and the
396
caught object declaration.
400
If you must use Obj-C exceptions, format them as follows. However, see
401
<a href="#Avoid_Throwing_Exceptions">Avoid Throwing Exceptions</a> for
402
reasons why you <b>should not</b> be using exceptions.
408
@catch (NSException *ex) {
418
<STYLEPOINT title="Protocols">
420
There should not be a space between the type identifier and the name
421
of the protocol encased in angle brackets.
425
This applies to class declarations, instance variables, and method
426
delcarations. For example:
429
@interface MyProtocoledClass : NSObject<NSWindowDelegate> {
431
id<MyFancyDelegate> delegate_;
433
- (void)setDelegate:(id<MyFancyDelegate>)aDelegate;
441
<CATEGORY title="Naming">
444
Naming rules are very important in maintainable code. Objective-C method
445
names tend to be very long, but this has the benefit that a block of code
446
can almost read like prose, thus rendering many comments unnecessary. </p>
447
<p> When writing pure Objective-C code, we mostly follow standard <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html">Objective-C
448
naming rules</a>. These naming guidelines may differ
449
significantly from those outlined in the C++ style guide. For example,
450
Google's C++ style guide recommends the use of underscores between words
451
in variable names, whereas this guide recommends the use of intercaps,
452
which is standard in the Objective-C community.
455
Any class, category, method, or variable name may use all capitals for
456
<a href="http://en.wikipedia.org/wiki/Initialism">initialisms</a>
457
within the name. This follows Apple's standard of using all capitals
458
within a name for initialisms such as URL, TIFF, and EXIF.
461
When writing Objective-C++, however, things are not so cut and dry. Many
462
projects need to implement cross-platform C++ APIs with some Objective-C
463
or Cocoa, or bridge between a C++ back-end and a native Cocoa front-end.
464
This leads to situations where the two guides are directly at odds.
467
Our solution is that the style follows that of the method/function being
468
implemented. If you're in an <code>@implementation</code> block, use the
469
Objective-C naming rules. If you're implementing a method for a C++
470
<code>class</code>, use the C++ naming rules. This avoids the situation
471
where instance variable and local variable naming rules are mixed within a
472
single function, which would be a serious detriment to readability.
475
<STYLEPOINT title="File Names">
477
File names should reflect the name of the class implementation that
478
they contain -- including case. Follow the convention that your
485
File extensions should be as follows:
489
<td><code>.h</code></td>
490
<td>C/C++/Objective-C header file</td>
493
<td><code>.m</code></td>
494
<td>Objective-C implementation file</td>
497
<td><code>.mm</code></td>
498
<td>Objective-C++ implementation file</td>
501
<td><code>.cc</code></td>
502
<td>Pure C++ implementation file</td>
505
<td><code>.c</code></td>
506
<td>C implementation file</td>
510
File names for categories should include the name of the class being
511
extended, e.g. <code>GTMNSString+Utils.h</code> or
512
<code>GTMNSTextView+Autocomplete.h</code>
517
<STYLEPOINT title="Objective-C++">
519
Within a source file, Objective-C++ follows the style of the
520
function/method you're implementing.
524
In order to minimize clashes between the differing naming styles when
525
mixing Cocoa/Objective-C and C++, follow the style of the method being
526
implemented. If you're in an <code>@implementation</code> block, use
527
the Objective-C naming rules. If you're implementing a method for a
528
C++ <code>class</code>, use the C++ naming rules.
531
// file: cross_platform_header.h
533
class CrossPlatformAPI {
536
int DoSomethingPlatformSpecific(); // impl on each platform
538
int an_instance_var_;
541
// file: mac_implementation.mm
542
#include "cross_platform_header.h"
544
// A typical Objective-C class, using Objective-C naming.
545
@interface MyDelegate : NSObject {
548
CrossPlatformAPI* backEndObject_;
550
- (void)respondToSomething:(id)something;
552
@implementation MyDelegate
553
- (void)respondToSomething:(id)something {
554
// bridge from Cocoa through our C++ backend
555
instanceVar_ = backEndObject->DoSomethingPlatformSpecific();
556
NSString* tempString = [NSString stringWithInt:instanceVar_];
557
NSLog(@"%@", tempString);
561
// The platform-specific implementation of the C++ class, using
563
int CrossPlatformAPI::DoSomethingPlatformSpecific() {
564
NSString* temp_string = [NSString stringWithInt:an_instance_var_];
565
NSLog(@"%@", temp_string);
566
return [temp_string intValue];
572
<STYLEPOINT title="Class Names">
574
Class names (along with category and protocol names) should start as
575
uppercase and use mixed case to delimit words.
579
In <em>application-level</em> code, prefixes on class names should
580
generally be avoided. Having every single class with same prefix
581
impairs readability for no benefit. When designing code to be shared
582
across multiple applications, prefixes are acceptable and recommended
583
(e.g. <code>GTMSendMessage</code>).
589
<STYLEPOINT title="Category Names">
591
Category names should start with a 2 or 3 character prefix
592
identifying the category as part of a project or open for general
593
use. The category name should incorporate the name of the class it's
598
For example, if we want to create a category on <code>NSString</code>
599
for parsing, we would put the category in a file named
600
<code>GTMNSString+Parsing.h</code>, and the category itself would be
601
named <code>GTMStringParsingAdditions</code> (yes, we know the file
602
name and the category name do not match, but this file could have many
603
separate categories related to parsing). Methods in that category
604
should share the prefix (<code>gtm_myCategoryMethodOnAString:</code>)
605
in order to prevent collisions in Objective-C which only has a single
606
namespace. If the code isn't meant to be shared and/or doesn't run in
607
a different address-space, the method naming isn't quite as
611
There should be a single space between the class name and the opening
612
parenthesis of the category.
617
<STYLEPOINT title="Objective-C Method Names">
619
Method names should start as lowercase and then use mixed case.
620
Each named parameter should also start as lowercase.
624
The method name should read like a sentence if possible, meaning you
625
should choose parameter names that flow with the method name. (e.g.
626
<code>convertPoint:fromRect:</code> or
627
<code>replaceCharactersInRange:withString:</code>). See <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282-BCIGIJJF">Apple's
628
Guide to Naming Methods</a> for more details.
631
Accessor methods should be named the same as the variable they're
632
"getting", but they should <em>not</em> be prefixed with the word
635
- (id)getDelegate; // AVOID
638
- (id)delegate; // GOOD
642
This is for Objective-C methods only. C++ method names and functions
643
continue to follow the rules set in the C++ style guide.
648
<STYLEPOINT title="Variable Names">
650
Variables names start with a lowercase and use mixed case to delimit
651
words. Class member variables have trailing underscores. For example:
652
<var>myLocalVariable</var>, <var>myInstanceVariable_</var>. Members
653
used for KVO/KVC bindings may begin with a leading underscore
654
<i>iff</i> use of Objective-C 2.0's <code>@property</code> isn't
658
<SUBSECTION title="Common Variable Names">
660
Do <em>not</em> use Hungarian notation for syntactic attributes,
661
such as the static type of a variable (int or pointer). Give as
662
descriptive a name as possible, within reason. Don't worry about
663
saving horizontal space as it is far more important to make your
664
code immediately understandable by a new reader. For example:
670
tix = [[NSMutableArray alloc] init];
671
obj = [someObject object];
676
int numCompletedConnections;
677
tickets = [[NSMutableArray alloc] init];
678
userInfo = [someObject object];
679
port = [network port];
683
<SUBSECTION title="Instance Variables">
685
Instance variables are mixed case and should be suffixed with a
686
trailing underscore, e.g. <var>usernameTextField_</var>. However,
687
we permit an exception when binding to a member variable using
688
KVO/KVC and Objective-C 2.0 cannot be used (due to OS release
689
constraints). In this case, it is acceptable to prefix the variable
690
with an underscore, per Apple's accepted practices for key/value
691
naming. If Objective-C 2.0 can be used, <code>@property</code> and
692
<code>@synthesize</code> provide a solution that conforms to the
697
<SUBSECTION title="Constants">
699
Constant names (#defines, enums, const local variables, etc.) should
700
start with a lowercase <var>k</var> and then use mixed case to
701
delimit words, i.e. <var>kInvalidHandle</var>,
702
<var>kWritePerm</var>.
710
<CATEGORY title="Comments">
713
Though a pain to write, they are absolutely vital to keeping our code
714
readable. The following rules describe what you should comment and where.
715
But remember: while comments are very important, the best code is
716
self-documenting. Giving sensible names to types and variables is much
717
better than using obscure names and then trying to explain them through
721
When writing your comments, write for your audience: the next
724
who will need to understand your code. Be generous — the next
728
Remember that all of the rules and conventions listed in the C++ Style
729
Guide are in effect here, with a few additional points, below.
732
<STYLEPOINT title="File Comments">
734
Start each file with a copyright notice, followed by a
735
description of the contents of the file.
738
<SUBSECTION title="Legal Notice and Author Line">
742
Every file should contain the following items, in order:
744
<li>a copyright statement (for example,
745
<code>Copyright 2008 Google Inc.</code>)</li>
746
<li>a license boilerplate. Choose the appropriate boilerplate
747
for the license used by the project (for example,
748
Apache 2.0, BSD, LGPL, GPL)</li>
752
If you make significant changes to a file that someone else
753
originally wrote, add yourself to the author line. This can
754
be very helpful when another
757
has questions about the file and needs to know whom to contact
764
<STYLEPOINT title="Declaration Comments">
766
Every interface, category, and protocol declaration should have an
767
accompanying comment describing its purpose and how it fits into the
772
// A delegate for NSApplication to handle notifications about app
773
// launch and shutdown. Owned by the main app controller.
774
@interface MyAppDelegate : NSObject {
780
If you have already described an interface in detail in the
781
comments at the top of your file feel free to simply state
782
"See comment at top of file for a complete description", but
783
be sure to have some sort of comment.
786
Additionally, each method in the public interface should have a
787
comment explaining its function, arguments, return value, and any
791
Document the synchronization assumptions the class makes, if
792
any. If an instance of the class can be accessed by multiple
793
threads, take extra care to document the rules and invariants
794
surrounding multithreaded use.
799
<STYLEPOINT title="Implementation Comments">
801
Use vertical bars to quote variable names and symbols in comments rather
802
than quotes or naming the symbol inline.
806
This helps eliminate ambiguity, especially when the symbol is a common
807
word that might make the sentence read like it was poorly constructed.
808
E.g. for a symbol "count":
811
// Sometimes we need |count| to be less than zero.
814
or when quoting something which already contains quotes
817
// Remember to call |StringWithoutSpaces("foo bar baz")|
822
<STYLEPOINT title="Object Ownership">
824
Make the pointer ownership model as explicit as possible when it falls
825
outside the most common Objective-C usage idioms.
829
Instance variable pointers to objects derived from NSObject are
830
presumed to be retained, and should be documented as <b>weak</b> if
831
they are not retained by the class. However, instance variables which
832
are labeled as IBOutlets are presumed to not be retained by the class,
833
and should be documented as <b>strong</b> if the class does retain
837
Where instance variables are pointers to CoreFoundation, C++, and
838
other non-Objective-C objects, they should always be documented in
839
comments as strong or weak. Be mindful that support for automatic C++
840
objects encapsulated in Objective-C objects is disabled by default, as
841
described <a href="http://chanson.livejournal.com/154253.html">here</a>.
844
Examples of strong and weak documentation:
846
@interface MyDelegate : NSObject {
848
IBOutlet NSButton* okButton_; // normal NSControl
849
IBOutlet NSMenu* myContextMenu_; // manually-loaded menu (strong)
851
AnObjcObject* doohickey_; // my doohickey
852
MyController* controller_; // so we can send msgs back (weak, owns me)
854
// non-NSObject pointers...
855
CWackyCPPClass* wacky_; // some cross-platform object (strong)
856
CFDictionaryRef* dict_; // (strong)
861
<dt>strong</dt><dd>The object will be <code>retain</code>'d by this class</dd>
862
<dt>weak</dt><dd>The object will be <b>not</b> be <code>retain</code>'d by this class
863
(e.g. a delegate).</dd>
871
<CATEGORY title="Cocoa and Objective-C Features">
873
<STYLEPOINT title="Member Variables Should Be @private">
875
Member variables should be declared <code>@private</code>.
879
@interface MyClass : NSObject {
881
id myInstanceVariable_;
883
// public accessors, setter takes ownership
884
- (id)myInstanceVariable;
885
- (void)setMyInstanceVariable:(id)theVar;
891
<STYLEPOINT title="Identify Designated Initializer">
893
Comment and clearly identify your designated initializer.
897
It is important for those who might be subclassing your class that the
898
designated initializer be clearly identified. That way, they only need
899
to subclass a single initializer (of potentially several) to guarantee
900
their subclass' initializer is called. It also helps those debugging
901
your class in the future understand the flow of initialization code if
902
they need to step through it.
907
<STYLEPOINT title="Override Designated Initializer">
909
When writing a subclass that requires an <code>init...</code> method,
910
make <i>sure</i> you override the superclass' designated initializer.
914
If you fail to override the superclass' designated initializer, your
915
initializer may not be called in all cases, leading to subtle and
916
very difficult to find bugs.
921
<STYLEPOINT title="Initialization">
923
Don't initialize variables to <code>0</code> or <code>nil</code> in the
924
init method; it's redundant.
928
All memory for a newly allocated object is initialized to 0 (except
929
for <var>isa</var>), so don't clutter up the <code>init</code> method
930
by re-initializing variables to 0 or <code>nil</code>.
935
<STYLEPOINT title="Keep the Public API Simple">
937
Keep your class simple; avoid "kitchen-sink" APIs. If a method doesn't
938
need to be public, don't make it so. Use a private category to prevent
939
cluttering the public header.
943
Unlike C++, Objective-C doesn't have a way to differentiate between
944
public and private methods — everything is public. As a result,
945
avoid placing methods in the public API unless they are actually
946
expected to be used by a consumer of the class. This helps reduce the
947
likelihood they'll be called when you're not expecting it. This includes
948
methods that are being overridden from the parent class. For internal
949
implementation methods, use a category defined in the implementation
950
file as opposed to adding them to the public header.
956
@interface GTMFoo (PrivateDelegateHandling)
957
- (NSString *)doSomethingWithDelegate; // Declare private method
960
@implementation GTMFoo(PrivateDelegateHandling)
962
- (NSString *)doSomethingWithDelegate {
963
// Implement this method
969
Before Objective-C 2.0, if you declare a method in the private
970
<code>@interface</code>, but forget to implement it in the main
971
<code>@implementation</code>, the compiler will <i>not</i> object.
972
(This is because you don't implement these private methods in a
973
separate category.) The solution is to put the functions within
974
an <code>@implementation</code> that specifies the category.
977
If you are using Objective-C 2.0, you should instead declare your
978
private category using a <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_4_section_5.html#">class
979
extension</a>, for example:
982
@interface GMFoo () { ... }
985
which will guarantee that the declared methods are implemented in the
986
<code>@implementation</code> section by issuing a compiler warning if
990
Again, "private" methods are not really private. You could
991
accidentally override a superclass's "private" method, thus making a
992
very difficult bug to squash. In general, private methods should have
993
a fairly unique name that will prevent subclasses from unintentionally
997
Finally, Objective-C categories are a great way to segment a large
998
<code>@implementation</code> section into more understandable chunks
999
and to add new, application-specific functionality to the most
1000
appropriate class. For example, instead of adding "middle truncation"
1001
code to a random object in your app, make a new category on
1002
<code>NSString</code>).
1007
<STYLEPOINT title="#import and #include">
1009
<code>#import</code> Objective-C/Objective-C++ headers, and
1010
<code>#include</code> C/C++ headers.
1014
Choose between <code>#import</code> and <code>#include</code> based
1015
on the language of the header that you are including.
1018
<li>When including a header that uses Objective-C or Objective-C++,
1019
use <code>#import</code>.</li>
1020
<li>When including a standard C or C++ header, use
1021
<code>#include</code>. The header should provide its own <a href="cppguide.xml?showone=The__define_Guard#The__define_Guard">#define
1025
Some Objective-C headers lack <code>#define</code> guards, and expect
1026
to be included only by <code>#import</code>. As Objective-C headers
1027
may only be included in Objective-C source files and other Objective-C
1028
headers, using <code>#import</code> across the board is appropriate.
1031
Standard C and C++ headers without any Objective-C in them can expect
1032
to be included by ordinary C and C++ files. Since there is no
1033
<code>#import</code> in standard C or C++, such files will be
1034
included by <code>#include</code> in those cases. Using
1035
<code>#include</code> for them in Objective-C source files as well
1036
means that these headers will always be included with the same
1040
This rule helps avoid inadvertent errors in cross-platform
1041
projects. A Mac developer introducing a new C or C++ header might
1042
forget to add <code>#define</code> guards, which would not cause
1043
problems on the Mac if the new header were included with
1044
<code>#import</code>, but would break builds on other platforms
1045
where <code>#include</code> is used. Being consistent by using
1046
<code>#include</code> on all platforms means that compilation is
1047
more likely to succeed everywhere or fail everywhere, and avoids
1048
the frustration of files working only on some platforms.
1051
#import <Cocoa/Cocoa.h>
1052
#include <CoreFoundation/CoreFoundation.h>
1054
#include "base/basictypes.h"
1059
<STYLEPOINT title="Use Root Frameworks">
1061
Include root frameworks over individual files.
1065
While it may seem tempting to include individual system headers from a
1066
framework such as Cocoa or Foundation, in fact it's less work on the
1067
compiler if you include the top-level root framework. The root
1068
framework is generally pre-compiled and can be loaded much more
1069
quickly. In addition, remember to use <code>#import</code> rather than
1070
<code>#include</code> for Objective-C frameworks.
1073
#import <Foundation/Foundation.h> // good
1076
#import <Foundation/NSArray.h> // avoid
1077
#import <Foundation/NSString.h>
1083
<STYLEPOINT title="Prefer To autorelease At Time of Creation">
1085
When creating new temporary objects, <code>autorelease</code> them on
1086
the same line as you create them rather than a separate
1087
<code>release</code> later in the same method.
1091
While ever so slightly slower, this prevents someone from accidentally
1092
removing the <code>release</code> or inserting a <code>return</code>
1093
before it and introducing a memory leak. E.g.:
1096
// AVOID (unless you have a compelling performance reason)
1097
MyController* controller = [[MyController alloc] init];
1098
// ... code here that might return ...
1099
[controller release];
1103
MyController* controller = [[[MyController alloc] init] autorelease];
1108
<STYLEPOINT title="Autorelease Then Retain">
1110
Assignment of objects follows the <code>autorelease</code> then
1111
<code>retain</code> pattern.
1115
When assigning a new object to a variable, one must first release the
1116
old object to avoid a memory leak. There are several "correct" ways to
1117
handle this. We've chosen the "autorelease then retain" approach
1118
because it's less prone to error. Be aware in tight loops it can fill
1119
up the autorelease pool, and may be slightly less efficient, but we
1120
feel the tradeoffs are acceptable.
1123
- (void)setFoo:(GMFoo *)aFoo {
1124
[foo_ autorelease]; // Won't dealloc if |foo_| == |aFoo|
1125
foo_ = [aFoo retain];
1131
<STYLEPOINT title="dealloc should process instance variables in declaration order">
1133
<code>dealloc</code> should process instance variables in the same order
1134
the <code>@interface</code> declares them, so it is easier for a reviewer
1139
A code reviewer checking a new or revised <code>dealloc</code>
1140
implementation needs to make sure that every retained instance
1141
variable gets released.
1144
To simplify reviewing <code>dealloc</code>, order the code so that
1145
the retained instance variables get released in the same order that
1146
they are declared in the <code>@interface</code>. If
1147
<code>dealloc</code> invokes other methods that release instance
1148
variables, add comments describing what instance variables those
1154
<STYLEPOINT title="Setters copy NSStrings">
1156
Setters taking an <code>NSString</code>, should always <code>copy</code>
1157
the string it accepts.
1161
Never just <code>retain</code> the string. This avoids the caller
1162
changing it under you without your knowledge. Don't assume that
1163
because you're accepting an <code>NSString</code> that it's not
1164
actually an <code>NSMutableString</code>.
1167
- (void)setFoo:(NSString *)aFoo {
1175
<STYLEPOINT title="Avoid Throwing Exceptions">
1177
Don't <code>@throw</code> Objective-C exceptions, but you should be
1178
prepared to catch them from third-party or OS calls.
1182
We do compile with <code>-fobjc-exceptions</code> (mainly so we get
1183
<code>@synchronized</code>), but we don't <code>@throw</code>. Use of
1184
<code>@try</code>, <code>@catch</code>, and <code>@finally</code> are
1185
allowed when required to properly use 3rd party code or libraries. If
1186
you do use them please document exactly which methods you expect to
1190
Do not use the <code>NS_DURING</code>, <code>NS_HANDLER</code>,
1191
<code>NS_ENDHANDLER</code>, <code>NS_VALUERETURN</code> and
1192
<code>NS_VOIDRETURN</code> macros unless you are writing code that
1193
needs to run on Mac OS X 10.2 or before.
1196
Also be aware when writing Objective-C++ code that stack based objects
1197
are <b>not</b> cleaned up when you throw an Objective-C exception.
1201
class exceptiontest {
1203
exceptiontest() { NSLog(@"Created"); }
1204
~exceptiontest() { NSLog(@"Destroyed"); }
1209
NSException *exception = [NSException exceptionWithName:@"foo"
1215
int main(int argc, char *argv[]) {
1216
GMAutoreleasePool pool;
1220
@catch(NSException *ex) {
1221
NSLog(@"exception raised");
1230
2006-09-28 12:34:29.244 exceptiontest[23661] Created
1231
2006-09-28 12:34:29.244 exceptiontest[23661] exception raised
1234
Note that the destructor for <i>a</i> never got called. This is a
1235
major concern for stack based smartptrs such as
1236
<code>shared_ptr</code> and <code>linked_ptr</code>, as well as any
1237
STL objects that you may want to use. Therefore it pains us to say
1238
that if you must use exceptions in your Objective-C++ code, use C++
1239
exceptions whenever possible. You should never re-throw an Objective-C
1240
exception, nor are stack based C++ objects (such as
1241
<code>std::string</code>, <code>std::vector</code> etc.) allowed in
1242
the body of any <code>@try</code>, <code>@catch</code>, or
1243
<code>@finally</code> blocks.
1249
<STYLEPOINT title="nil Checks">
1251
Use <code>nil</code> checks for logic flow only.
1255
Use <code>nil</code> checks for logic flow of the application, not for
1256
crash prevention. Sending a message to a <code>nil</code> object is
1257
handled by the Objective-C runtime. If the method has no return
1258
result, you're good to go. However if there is one, there may be
1259
differences based on runtime architecture, return size, and OS X
1260
version (see <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_2_section_3.html#//apple_ref/doc/uid/TP30001163-CH11-SW7">Apple's
1261
documentation</a> for specifics).
1264
Note that this is very different from checking C/C++ pointers against
1265
<code>NULL</code>, which the runtime does not handle and will cause
1266
your application to crash. You still need to make sure you do not
1267
dereference a <code>NULL</code> pointer.
1272
<STYLEPOINT title="BOOL Pitfalls">
1274
Be careful when converting general integral values to <code>BOOL</code>.
1275
Avoid comparing directly with <code>YES</code>.
1279
<code>BOOL</code> is defined as an unsigned char in Objective-C which
1280
means that it can have values other than <code>YES</code> (1) and
1281
<code>NO</code> (0). Do not cast or convert general integral values
1282
directly to <code>BOOL</code>. Common mistakes include casting or
1283
converting an array's size, a pointer value, or the result of a bitwise
1284
logic operation to a <code>BOOL</code> which, depending on the value of
1285
the last byte of the integral result, could still result in a
1286
<code>NO</code> value. When converting a general integral value to a
1287
<code>BOOL</code> use ternery operators to return a <code>YES</code>
1288
or <code>NO</code> value.
1291
You can safely interchange and convert <code>BOOL</code>,
1292
<code>_Bool</code> and <code>bool</code> (see C++ Std 4.7.4, 4.12 and
1293
C99 Std 6.3.1.2). You cannot safely interchange <code>BOOL</code> and
1294
<code>Boolean</code> so treat <code>Booleans</code> as a general
1295
integral value as discussed above. Only use <code>BOOL</code> in
1296
Objective C method signatures.
1299
Using logical operators (<code>&&</code>, <code>||</code> and
1300
<code>!</code>) with <code>BOOL</code> is also valid and will return
1301
values that can be safely converted to <code>BOOL</code> without the
1302
need for a ternery operator.
1306
return [self fontTraits] & NSFontBoldTrait;
1309
return [self stringValue];
1314
return ([self fontTraits] & NSFontBoldTrait) ? YES : NO;
1317
return [self stringValue] != nil;
1320
return [self isValid] && [self isBold];
1324
Also, don't directly compare <code>BOOL</code> variables directly
1325
with <code>YES</code>. Not only is it harder to read for those
1326
well-versed in C, the first point above demonstrates that return
1327
values may not always be what you expect.
1330
BOOL great = [foo isGreat];
1335
BOOL great = [foo isGreat];
1343
<STYLEPOINT title="Properties">
1345
Properties in general are allowed with the following caveat: properties
1346
are an Objective-C 2.0 feature which will limit your code to running
1347
on the iPhone and Mac OS X 10.5 (Leopard) and higher. Dot notation
1348
is allowed only for access to a declared <code>@property</code>.
1351
<SUBSECTION title="Naming">
1353
A property's associated instance variable's name must conform to the
1354
trailing _ requirement. The property's name should be the same as its
1355
associated instance variable without the trailing _.
1358
Use the @synthesize directive to rename the property correctly.
1362
@interface MyClass : NSObject {
1366
@property(copy, nonatomic) NSString *name;
1369
@implementation MyClass
1370
@synthesize name = name_;
1374
<SUBSECTION title="Location">
1376
A property's declaration must come immediately after the instance
1377
variable block of a class interface. A property's definition must
1378
come immediately after the <code>@implementation</code> block in a
1379
class definition. They are indented at the same level as the
1380
<code>@interface</code> or <code>@implementation</code> statements
1381
that they are enclosed in.
1384
@interface MyClass : NSObject {
1388
@property(copy, nonatomic) NSString *name;
1391
@implementation MyClass
1392
@synthesize name = name_;
1399
<SUBSECTION title="Use Copy Attribute For Strings">
1401
NSString properties should always be declared with the
1402
<code>copy</code> attribute.
1405
This logically follows from the requirement that setters for
1406
NSStrings always must use <code>copy</code> instead of
1407
<code>retain</code>.
1410
<SUBSECTION title="Never synthesize CFType properties">
1412
CFTypes should always have the <code>@dynamic</code> implementation
1416
Since CFTypes can't have the <code>retain</code> property
1417
attribute, the developer must handle retaining and releasing the
1418
value themselves. In the rare case that you do actually want
1419
assignment it is better to make that completely clear by actually
1420
implementing the setter and getter and commenting why that is the
1424
<SUBSECTION title="List out all implementation directives">
1426
Use implementation directives for all properties even if they are
1427
<code>@dynamic</code> by default.
1430
Even though <code>@dynamic</code> is default, explicitly list it out
1431
with all of the other property implementation directives making it
1432
clear how every property in a class is handled at a single glance.
1435
@interface MyClass : NSObject
1436
@property(readonly) NSString *name;
1439
@implementation MyClass
1449
@interface MyClass : NSObject
1450
@property(readonly) NSString *name;
1453
@implementation MyClass
1464
<SUBSECTION title="Atomicity">
1466
Be aware of the overhead of properties. By default, all synthesized
1467
setters and getters are atomic. This gives each set and get calls a
1468
substantial amount of synchronization overhead. Declare your
1469
properties <code>nonatomic</code> unless you require atomicity.
1472
<SUBSECTION title="Dot notation">
1474
Dot notation is idiomatic style for Objective-C 2.0. It may be used
1475
when doing simple operations to get and set a <code>@property</code>
1476
of an object, but should not be used to invoke other object behavior.
1479
NSString *oldName = myObject.name;
1480
myObject.name = @"Alice";
1483
NSArray *array = [[NSArray arrayWithObject:@"hello"] retain];
1485
NSUInteger numberOfItems = array.count; // not a property
1486
array.release; // not a property
1494
<CATEGORY title="Cocoa Patterns">
1496
<STYLEPOINT title="Delegate Pattern">
1498
Delegate objects should not be retained.
1502
A class that implements the delegate pattern should:
1505
Have an instance variable named <var>delegate_</var> to reference
1509
Thus, the accessor methods should be named <code>delegate</code>
1510
and <code>setDelegate:</code>.
1513
The <var>delegate_</var> object should <b>not</b> be retained.
1520
<STYLEPOINT title="Model/View/Controller">
1522
Separate the model from the view. Separate the controller from the
1523
view and the model. Use <code>@protocol</code>s for callback APIs.
1529
Separate model from view: don't build assumptions about the
1530
presentation into the model or data source. Keep the interface
1531
between the data source and the presentation abstract. Don't give
1532
the model knowledge of its view. (A good rule of thumb is to ask
1533
yourself if it's possible to have multiple presentations, with
1534
different states, on a single instance of your data source.)
1537
Separate controller from view and model: don't put all of the
1538
"business logic" into view-related classes; this makes the code
1539
very unusable. Make controller classes to host this code, but
1540
ensure that the controller classes don't make too many assumptions
1541
about the presentation.
1544
Define callback APIs with <code>@protocol</code>, using
1545
<code>@optional</code> if not all the methods are required.
1546
(Exception: when using Objective-C 1.0, <code>@optional</code> isn't
1547
available, so use a category to define an "informal protocol".)
1565
Mike Pinkerton <br/>
1567
Dave MacLachlan <br/>