• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Google Objective-C Style Guide
2
3
4> Objective-C is a dynamic, object-oriented extension of C. It's designed to be
5> easy to use and read, while enabling sophisticated object-oriented design. It
6> is the primary development language for applications on OS X and on iOS.
7>
8> Apple has already written a very good, and widely accepted, [Cocoa Coding
9> Guidelines](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html)
10> for Objective-C. Please read it in addition to this guide.
11>
12>
13> The purpose of this document is to describe the Objective-C (and
14> Objective-C++) coding guidelines and practices that should be used for iOS and
15> OS X code. These guidelines have evolved and been proven over time on other
16> projects and teams.
17> Open-source projects developed by Google conform to the requirements in this guide.
18>
19> Note that this guide is not an Objective-C tutorial. We assume that the reader
20> is familiar with the language. If you are new to Objective-C or need a
21> refresher, please read [Programming with
22> Objective-C](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html).
23
24
25## Principles
26
27### Optimize for the reader, not the writer
28
29Codebases often have extended lifetimes and more time is spent reading the code
30than writing it. We explicitly choose to optimize for the experience of our
31average software engineer reading, maintaining, and debugging code in our
32codebase rather than the ease of writing said code. For example, when something
33surprising or unusual is happening in a snippet of code, leaving textual hints
34for the reader is valuable.
35
36### Be consistent
37
38When the style guide allows multiple options it is preferable to pick one option
39over mixed usage of multiple options. Using one style consistently throughout a
40codebase lets engineers focus on other (more important) issues. Consistency also
41enables better automation because consistent code allows more efficient
42development and operation of tools that format or refactor code. In many cases,
43rules that are attributed to "Be Consistent" boil down to "Just pick one and
44stop worrying about it"; the potential value of allowing flexibility on these
45points is outweighed by the cost of having people argue over them.
46
47### Be consistent with Apple SDKs
48
49Consistency with the way Apple SDKs use Objective-C has value for the same
50reasons as consistency within our code base. If an Objective-C feature solves a
51problem that's an argument for using it. However, sometimes language features
52and idioms are flawed, or were just designed with assumptions that are not
53universal. In those cases it is appropriate to constrain or ban language
54features or idioms.
55
56### Style rules should pull their weight
57
58The benefit of a style rule must be large enough to justify asking engineers to
59remember it. The benefit is measured relative to the codebase we would get
60without the rule, so a rule against a very harmful practice may still have a
61small benefit if people are unlikely to do it anyway. This principle mostly
62explains the rules we don’t have, rather than the rules we do: for example, goto
63contravenes many of the following principles, but is not discussed due to its
64extreme rarity.
65
66## Example
67
68They say an example is worth a thousand words, so let's start off with an
69example that should give you a feel for the style, spacing, naming, and so on.
70
71Here is an example header file, demonstrating the correct commenting and spacing
72for an `@interface` declaration.
73
74```objectivec
75// GOOD:
76
77#import <Foundation/Foundation.h>
78
79@class Bar;
80
81/**
82 * A sample class demonstrating good Objective-C style. All interfaces,
83 * categories, and protocols (read: all non-trivial top-level declarations
84 * in a header) MUST be commented. Comments must also be adjacent to the
85 * object they're documenting.
86 */
87@interface Foo : NSObject
88
89/** The retained Bar. */
90@property(nonatomic) Bar *bar;
91
92/** The current drawing attributes. */
93@property(nonatomic, copy) NSDictionary<NSString *, NSNumber *> *attributes;
94
95/**
96 * Convenience creation method.
97 * See -initWithBar: for details about @c bar.
98 *
99 * @param bar The string for fooing.
100 * @return An instance of Foo.
101 */
102+ (instancetype)fooWithBar:(Bar *)bar;
103
104/**
105 * Initializes and returns a Foo object using the provided Bar instance.
106 *
107 * @param bar A string that represents a thing that does a thing.
108 */
109- (instancetype)initWithBar:(Bar *)bar NS_DESIGNATED_INITIALIZER;
110
111/**
112 * Does some work with @c blah.
113 *
114 * @param blah
115 * @return YES if the work was completed; NO otherwise.
116 */
117- (BOOL)doWorkWithBlah:(NSString *)blah;
118
119@end
120```
121
122An example source file, demonstrating the correct commenting and spacing for the
123`@implementation` of an interface.
124
125```objectivec
126// GOOD:
127
128#import "Shared/Util/Foo.h"
129
130@implementation Foo {
131  /** The string used for displaying "hi". */
132  NSString *_string;
133}
134
135+ (instancetype)fooWithBar:(Bar *)bar {
136  return [[self alloc] initWithBar:bar];
137}
138
139- (instancetype)init {
140  // Classes with a custom designated initializer should always override
141  // the superclass's designated initializer.
142  return [self initWithBar:nil];
143}
144
145- (instancetype)initWithBar:(Bar *)bar {
146  self = [super init];
147  if (self) {
148    _bar = [bar copy];
149    _string = [[NSString alloc] initWithFormat:@"hi %d", 3];
150    _attributes = @{
151      @"color" : [UIColor blueColor],
152      @"hidden" : @NO
153    };
154  }
155  return self;
156}
157
158- (BOOL)doWorkWithBlah:(NSString *)blah {
159  // Work should be done here.
160  return NO;
161}
162
163@end
164```
165
166## Naming
167
168Names should be as descriptive as possible, within reason. Follow standard
169[Objective-C naming
170rules](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html).
171
172Avoid non-standard abbreviations (including non-standard acronyms and
173initialisms). Don't worry about saving horizontal space as it is far more
174important to make your code immediately understandable by a new reader. For
175example:
176
177```objectivec
178// GOOD:
179
180// Good names.
181int numberOfErrors = 0;
182int completedConnectionsCount = 0;
183tickets = [[NSMutableArray alloc] init];
184userInfo = [someObject object];
185port = [network port];
186NSDate *gAppLaunchDate;
187```
188
189```objectivec
190// AVOID:
191
192// Names to avoid.
193int w;
194int nerr;
195int nCompConns;
196tix = [[NSMutableArray alloc] init];
197obj = [someObject object];
198p = [network port];
199```
200
201Any class, category, method, function, or variable name should use all capitals
202for acronyms and
203[initialisms](https://en.wikipedia.org/wiki/Initialism)
204within the name. This follows Apple's standard of using all capitals within a
205name for acronyms such as URL, ID, TIFF, and EXIF.
206
207Names of C functions and typedefs should be capitalized and use camel case as
208appropriate for the surrounding code.
209
210### File Names
211
212File names should reflect the name of the class implementation that they
213contain—including case.
214
215Follow the convention that your project uses.
216File extensions should be as follows:
217
218Extension | Type
219--------- | ---------------------------------
220.h        | C/C++/Objective-C header file
221.m        | Objective-C implementation file
222.mm       | Objective-C++ implementation file
223.cc       | Pure C++ implementation file
224.c        | C implementation file
225
226Files containing code that may be shared across projects or used in a large
227project should have a clearly unique name, typically including the project or
228class [prefix](#prefixes).
229
230File names for categories should include the name of the class being extended,
231like GTMNSString+Utils.h or NSTextView+GTMAutocomplete.h
232
233### Prefixes
234
235Prefixes are commonly required in Objective-C to avoid naming collisions in a
236global namespace. Classes, protocols, global functions, and global constants
237should generally be named with a prefix that begins with a capital letter
238followed by one or more capital letters or numbers.
239
240WARNING: Apple reserves two-letter prefixes—see
241[Conventions in Programming with Objective-C](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Conventions/Conventions.html)—so
242prefixes with a minimum of three characters are considered best practice.
243
244```objectivec
245// GOOD:
246
247/** An example error domain. */
248extern NSString *GTMExampleErrorDomain;
249
250/** Gets the default time zone. */
251extern NSTimeZone *GTMGetDefaultTimeZone(void);
252
253/** An example delegate. */
254@protocol GTMExampleDelegate <NSObject>
255@end
256
257/** An example class. */
258@interface GTMExample : NSObject
259@end
260
261```
262
263### Class Names
264
265Class names (along with category and protocol names) should start as uppercase
266and use mixed case to delimit words.
267
268Classes and protocols in code shared across multiple applications must have an
269appropriate [prefix](#prefixes) (e.g. GTMSendMessage). Prefixes are recommended,
270but not required, for other classes and protocols.
271
272### Category Naming
273
274Category names should start with an appropriate [prefix](#prefixes) identifying
275the category as part of a project or open for general use.
276
277Category source file names should begin with the class being extended followed
278by a plus sign and the name of the category, e.g., `NSString+GTMParsing.h`.
279Methods in a category should be prefixed with a lowercase version of the prefix
280used for the category name followed by an underscore (e.g.,
281`gtm_myCategoryMethodOnAString:`) in order to prevent collisions in
282Objective-C's global namespace.
283
284There should be a single space between the class name and the opening
285parenthesis of the category.
286
287```objectivec
288// GOOD:
289
290// UIViewController+GTMCrashReporting.h
291
292/** A category that adds metadata to include in crash reports to UIViewController. */
293@interface UIViewController (GTMCrashReporting)
294
295/** A unique identifier to represent the view controller in crash reports. */
296@property(nonatomic, setter=gtm_setUniqueIdentifier:) int gtm_uniqueIdentifier;
297
298/** Returns an encoded representation of the view controller's current state. */
299- (nullable NSData *)gtm_encodedState;
300
301@end
302```
303
304If a class is not shared with other projects, categories extending it may omit
305name prefixes and method name prefixes.
306
307```objectivec
308// GOOD:
309
310/** This category extends a class that is not shared with other projects. */
311@interface XYZDataObject (Storage)
312- (NSString *)storageIdentifier;
313@end
314```
315
316### Objective-C Method Names
317
318Method and parameter names typically start as lowercase and then use mixed case.
319
320Proper capitalization should be respected, including at the beginning of names.
321
322```objectivec
323// GOOD:
324
325+ (NSURL *)URLWithString:(NSString *)URLString;
326```
327
328The method name should read like a sentence if possible, meaning you should
329choose parameter names that flow with the method name. Objective-C method names
330tend to be very long, but this has the benefit that a block of code can almost
331read like prose, thus rendering many implementation comments unnecessary.
332
333Use prepositions and conjunctions like "with", "from", and "to" in the second
334and later parameter names only where necessary to clarify the meaning or
335behavior of the method.
336
337```objectivec
338// GOOD:
339
340- (void)addTarget:(id)target action:(SEL)action;                          // GOOD; no conjunction needed
341- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;           // GOOD; conjunction clarifies parameter
342- (void)replaceCharactersInRange:(NSRange)aRange
343            withAttributedString:(NSAttributedString *)attributedString;  // GOOD.
344```
345
346A method that returns an object should have a name beginning with a noun
347identifying the object returned:
348
349```objectivec
350// GOOD:
351
352- (Sandwich *)sandwich;      // GOOD.
353```
354
355```objectivec
356// AVOID:
357
358- (Sandwich *)makeSandwich;  // AVOID.
359```
360
361An accessor method should be named the same as the object it's getting, but it
362should not be prefixed with the word `get`. For example:
363
364```objectivec
365// GOOD:
366
367- (id)delegate;     // GOOD.
368```
369
370```objectivec
371// AVOID:
372
373- (id)getDelegate;  // AVOID.
374```
375
376Accessors that return the value of boolean adjectives have method names
377beginning with `is`, but property names for those methods omit the `is`.
378
379Dot notation is used only with property names, not with method names.
380
381```objectivec
382// GOOD:
383
384@property(nonatomic, getter=isGlorious) BOOL glorious;
385- (BOOL)isGlorious;
386
387BOOL isGood = object.glorious;      // GOOD.
388BOOL isGood = [object isGlorious];  // GOOD.
389```
390
391```objectivec
392// AVOID:
393
394BOOL isGood = object.isGlorious;    // AVOID.
395```
396
397```objectivec
398// GOOD:
399
400NSArray<Frog *> *frogs = [NSArray<Frog *> arrayWithObject:frog];
401NSEnumerator *enumerator = [frogs reverseObjectEnumerator];  // GOOD.
402```
403
404```objectivec
405// AVOID:
406
407NSEnumerator *enumerator = frogs.reverseObjectEnumerator;    // AVOID.
408```
409
410See [Apple's Guide to Naming
411Methods](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282-BCIGIJJF)
412for more details on Objective-C naming.
413
414These guidelines are for Objective-C methods only. C++ method names continue to
415follow the rules set in the C++ style guide.
416
417### Function Names
418
419Function names should start with a capital letter and have a capital letter for
420each new word (a.k.a. "[camel case](https://en.wikipedia.org/wiki/Camel_case)"
421or "Pascal case").
422
423```objectivec
424// GOOD:
425
426static void AddTableEntry(NSString *tableEntry);
427static BOOL DeleteFile(const char *filename);
428```
429
430Because Objective-C does not provide namespacing, non-static functions should
431have a [prefix](#prefixes) that minimizes the chance of a name collision.
432
433```objectivec
434// GOOD:
435
436extern NSTimeZone *GTMGetDefaultTimeZone(void);
437extern NSString *GTMGetURLScheme(NSURL *URL);
438```
439
440### Variable Names
441
442Variable names typically start with a lowercase and use mixed case to delimit
443words.
444
445Instance variables have leading underscores. File scope or global variables have
446a prefix `g`. For example: `myLocalVariable`, `_myInstanceVariable`,
447`gMyGlobalVariable`.
448
449#### Common Variable Names
450
451Readers should be able to infer the variable type from the name, but do not use
452Hungarian notation for syntactic attributes, such as the static type of a
453variable (int or pointer).
454
455File scope or global variables (as opposed to constants) declared outside the
456scope of a method or function should be rare, and should have the prefix g.
457
458```objectivec
459// GOOD:
460
461static int gGlobalCounter;
462```
463
464#### Instance Variables
465
466Instance variable names are mixed case and should be prefixed with an
467underscore, like `_usernameTextField`.
468
469NOTE: Google's previous convention for Objective-C ivars was a trailing
470underscore. Existing projects may opt to continue using trailing underscores in
471new code in order to maintain consistency within the project codebase.
472Consistency of prefix or suffix underscores should be maintained within each
473class.
474
475#### Constants
476
477Constant symbols (const global and static variables and constants created
478with #define) should use mixed case to delimit words.
479
480Global and file scope constants should have an appropriate [prefix](#prefixes).
481
482```objectivec
483// GOOD:
484
485extern NSString *const GTLServiceErrorDomain;
486
487typedef NS_ENUM(NSInteger, GTLServiceError) {
488  GTLServiceErrorQueryResultMissing = -3000,
489  GTLServiceErrorWaitTimedOut       = -3001,
490};
491```
492
493Because Objective-C does not provide namespacing, constants with external
494linkage should have a prefix that minimizes the chance of a name collision,
495typically like `ClassNameConstantName` or `ClassNameEnumName`.
496
497For interoperability with Swift code, enumerated values should have names that
498extend the typedef name:
499
500```objectivec
501// GOOD:
502
503typedef NS_ENUM(NSInteger, DisplayTinge) {
504  DisplayTingeGreen = 1,
505  DisplayTingeBlue = 2,
506};
507```
508
509A lowercase k can be used as a standalone prefix for constants of static storage
510duration declared within implementation files:
511
512```objectivec
513// GOOD:
514
515static const int kFileCount = 12;
516static NSString *const kUserKey = @"kUserKey";
517```
518
519NOTE: Previous convention was for public constant names to begin with a
520lowercase k followed by a project-specific [prefix](#prefixes). This practice is
521no longer recommended.
522
523## Types and Declarations
524
525### Method Declarations
526
527As shown in the [example](#Example), the recommended order
528for declarations in an `@interface` declaration are: properties, class methods,
529initializers, and then finally instance methods. The class methods section
530should begin with any convenience constructors.
531
532### Local Variables
533
534Declare variables in the narrowest practical scopes, and close to their use.
535Initialize variables in their declarations.
536
537```objectivec
538// GOOD:
539
540CLLocation *location = [self lastKnownLocation];
541for (int meters = 1; meters < 10; meters++) {
542  reportFrogsWithinRadius(location, meters);
543}
544```
545
546Occasionally, efficiency will make it more appropriate to declare a variable
547outside the scope of its use. This example declares meters separate from
548initialization, and needlessly sends the lastKnownLocation message each time
549through the loop:
550
551```objectivec
552// AVOID:
553
554int meters;                                         // AVOID.
555for (meters = 1; meters < 10; meters++) {
556  CLLocation *location = [self lastKnownLocation];  // AVOID.
557  reportFrogsWithinRadius(location, meters);
558}
559```
560
561Under Automatic Reference Counting, strong and weak pointers to Objective-C
562objects are automatically initialized to `nil`, so explicit initialization to
563`nil` is not required for those common cases. However, automatic initialization
564does *not* occur for many Objective-C pointer types, including object pointers
565declared with the `__unsafe_unretained` ownership qualifier and CoreFoundation
566object pointer types. When in doubt, prefer to initialize all Objective-C
567local variables.
568
569### Unsigned Integers
570
571Avoid unsigned integers except when matching types used by system interfaces.
572
573Subtle errors crop up when doing math or counting down to zero using unsigned
574integers. Rely only on signed integers in math expressions except when matching
575NSUInteger in system interfaces.
576
577```objectivec
578// GOOD:
579
580NSUInteger numberOfObjects = array.count;
581for (NSInteger counter = numberOfObjects - 1; counter > 0; --counter)
582```
583
584```objectivec
585// AVOID:
586
587for (NSUInteger counter = numberOfObjects - 1; counter > 0; --counter)  // AVOID.
588```
589
590Unsigned integers may be used for flags and bitmasks, though often NS_OPTIONS or
591NS_ENUM will be more appropriate.
592
593### Types with Inconsistent Sizes
594
595Due to sizes that differ in 32- and 64-bit builds, avoid types long, NSInteger,
596NSUInteger, and CGFloat except when matching system interfaces.
597
598Types long, NSInteger, NSUInteger, and CGFloat vary in size between 32- and
59964-bit builds. Use of these types is appropriate when handling values exposed by
600system interfaces, but they should be avoided for most other computations.
601
602```objectivec
603// GOOD:
604
605int32_t scalar1 = proto.intValue;
606
607int64_t scalar2 = proto.longValue;
608
609NSUInteger numberOfObjects = array.count;
610
611CGFloat offset = view.bounds.origin.x;
612```
613
614```objectivec
615// AVOID:
616
617NSInteger scalar2 = proto.longValue;  // AVOID.
618```
619
620File and buffer sizes often exceed 32-bit limits, so they should be declared
621using `int64_t`, not with `long`, `NSInteger`, or `NSUInteger`.
622
623## Comments
624
625Comments are absolutely vital to keeping our code readable. The following rules
626describe what you should comment and where. But remember: while comments are
627important, the best code is self-documenting. Giving sensible names to types and
628variables is much better than using obscure names and then trying to explain
629them through comments.
630
631Pay attention to punctuation, spelling, and grammar; it is easier to read
632well-written comments than badly written ones.
633
634Comments should be as readable as narrative text, with proper capitalization and
635punctuation. In many cases, complete sentences are more readable than sentence
636fragments. Shorter comments, such as comments at the end of a line of code, can
637sometimes be less formal, but use a consistent style.
638When writing your comments, write for your audience: the next contributor who will need to understand your code. Be generous—the next one may be you!
639
640### File Comments
641
642A file may optionally start with a description of its contents.
643Every file may contain the following items, in order:
644  * License boilerplate if necessary. Choose the appropriate boilerplate for the license used by the project.
645  * A basic description of the contents of the file if necessary.
646
647If you make significant changes to a file with an author line, consider deleting
648the author line since revision history already provides a more detailed and
649accurate record of authorship.
650
651
652### Declaration Comments
653
654Every non-trivial interface, public and private, should have an accompanying
655comment describing its purpose and how it fits into the larger picture.
656
657Comments should be used to document classes, properties, ivars, functions,
658categories, protocol declarations, and enums.
659
660```objectivec
661// GOOD:
662
663/**
664 * A delegate for NSApplication to handle notifications about app
665 * launch and shutdown. Owned by the main app controller.
666 */
667@interface MyAppDelegate : NSObject {
668  /**
669   * The background task in progress, if any. This is initialized
670   * to the value UIBackgroundTaskInvalid.
671   */
672  UIBackgroundTaskIdentifier _backgroundTaskID;
673}
674
675/** The factory that creates and manages fetchers for the app. */
676@property(nonatomic) GTMSessionFetcherService *fetcherService;
677
678@end
679```
680
681Doxygen-style comments are encouraged for interfaces as they are parsed by Xcode
682to display formatted documentation. There is a wide variety of Doxygen commands;
683use them consistently within a project.
684
685If you have already described an interface in detail in the comments at the top
686of your file, feel free to simply state, "See comment at top of file for a
687complete description", but be sure to have some sort of comment.
688
689Additionally, each method should have a comment explaining its function,
690arguments, return value, thread or queue assumptions, and any side effects.
691Documentation comments should be in the header for public methods, or
692immediately preceding the method for non-trivial private methods.
693
694Use descriptive form ("Opens the file") rather than imperative form ("Open the
695file") for method and function comments. The comment describes the function; it
696does not tell the function what to do.
697
698Document the thread usage assumptions the class, properties, or methods make, if
699any. If an instance of the class can be accessed by multiple threads, take extra
700care to document the rules and invariants surrounding multithreaded use.
701
702Any sentinel values for properties and ivars, such as `NULL` or `-1`, should be
703documented in comments.
704
705Declaration comments explain how a method or function is used. Comments
706explaining how a method or function is implemented should be with the
707implementation rather than with the declaration.
708
709### Implementation Comments
710
711Provide comments explaining tricky, subtle, or complicated sections of code.
712
713```objectivec
714// GOOD:
715
716// Set the property to nil before invoking the completion handler to
717// avoid the risk of reentrancy leading to the callback being
718// invoked again.
719CompletionHandler handler = self.completionHandler;
720self.completionHandler = nil;
721handler();
722```
723
724When useful, also provide comments about implementation approaches that were
725considered or abandoned.
726
727End-of-line comments should be separated from the code by at least 2 spaces. If
728you have several comments on subsequent lines, it can often be more readable to
729line them up.
730
731```objectivec
732// GOOD:
733
734[self doSomethingWithALongName];  // Two spaces before the comment.
735[self doSomethingShort];          // More spacing to align the comment.
736```
737
738### Disambiguating Symbols
739
740Where needed to avoid ambiguity, use backticks or vertical bars to quote
741variable names and symbols in comments in preference to using quotation marks
742or naming the symbols inline.
743
744In Doxygen-style comments, prefer demarcating symbols with a monospace text
745command, such as `@c`.
746
747Demarcation helps provide clarity when a symbol is a common word that might make
748the sentence read like it was poorly constructed. A common example is the symbol
749`count`:
750
751```objectivec
752// GOOD:
753
754// Sometimes `count` will be less than zero.
755```
756
757or when quoting something which already contains quotes
758
759```objectivec
760// GOOD:
761
762// Remember to call `StringWithoutSpaces("foo bar baz")`
763```
764
765Backticks or vertical bars are not needed when a symbol is self-apparent.
766
767```objectivec
768// GOOD:
769
770// This class serves as a delegate to GTMDepthCharge.
771```
772
773Doxygen formatting is also suitable for identifying symbols.
774
775```objectivec
776// GOOD:
777
778/** @param maximum The highest value for @c count. */
779```
780
781### Object Ownership
782
783For objects not managed by ARC, make the pointer ownership model as explicit as
784possible when it falls outside the most common Objective-C usage idioms.
785
786#### Manual Reference Counting
787
788Instance variables for NSObject-derived objects are presumed to be retained; if
789they are not retained, they should be either commented as weak or declared with
790the `__weak` lifetime qualifier.
791
792An exception is in Mac software for instance variables labeled as `@IBOutlets`,
793which are presumed to not be retained.
794
795Where instance variables are pointers to Core Foundation, C++, and other
796non-Objective-C objects, they should always be declared with strong and weak
797comments to indicate which pointers are and are not retained. Core Foundation
798and other non-Objective-C object pointers require explicit memory management,
799even when building for automatic reference counting.
800
801Examples of strong and weak declarations:
802
803```objectivec
804// GOOD:
805
806@interface MyDelegate : NSObject
807
808@property(nonatomic) NSString *doohickey;
809@property(nonatomic, weak) NSString *parent;
810
811@end
812
813
814@implementation MyDelegate {
815  IBOutlet NSButton *_okButton;  // Normal NSControl; implicitly weak on Mac only
816
817  AnObjcObject *_doohickey;  // My doohickey
818  __weak MyObjcParent *_parent;  // To send messages back (owns this instance)
819
820  // non-NSObject pointers...
821  CWackyCPPClass *_wacky;  // Strong, some cross-platform object
822  CFDictionaryRef *_dict;  // Strong
823}
824@end
825```
826
827#### Automatic Reference Counting
828
829Object ownership and lifetime are explicit when using ARC, so no additional
830comments are required for automatically retained objects.
831
832## C Language Features
833
834### Macros
835
836Avoid macros, especially where `const` variables, enums, XCode snippets, or C
837functions may be used instead.
838
839Macros make the code you see different from the code the compiler sees. Modern C
840renders traditional uses of macros for constants and utility functions
841unnecessary. Macros should only be used when there is no other solution
842available.
843
844Where a macro is needed, use a unique name to avoid the risk of a symbol
845collision in the compilation unit. If practical, keep the scope limited by
846`#undefining` the macro after its use.
847
848Macro names should use `SHOUTY_SNAKE_CASE`—all uppercase letters with
849underscores between words. Function-like macros may use C function naming
850practices. Do not define macros that appear to be C or Objective-C keywords.
851
852```objectivec
853// GOOD:
854
855#define GTM_EXPERIMENTAL_BUILD ...      // GOOD
856
857// Assert unless X > Y
858#define GTM_ASSERT_GT(X, Y) ...         // GOOD, macro style.
859
860// Assert unless X > Y
861#define GTMAssertGreaterThan(X, Y) ...  // GOOD, function style.
862```
863
864```objectivec
865// AVOID:
866
867#define kIsExperimentalBuild ...        // AVOID
868
869#define unless(X) if(!(X))              // AVOID
870```
871
872Avoid macros that expand to unbalanced C or Objective-C constructs. Avoid macros
873that introduce scope, or may obscure the capturing of values in blocks.
874
875Avoid macros that generate class, property, or method definitions in
876headers to be used as public API. These only make the code hard to
877understand, and the language already has better ways of doing this.
878
879Avoid macros that generate method implementations, or that generate declarations
880of variables that are later used outside of the macro. Macros shouldn't make
881code hard to understand by hiding where and how a variable is declared.
882
883```objectivec
884// AVOID:
885
886#define ARRAY_ADDER(CLASS) \
887  -(void)add ## CLASS ## :(CLASS *)obj toArray:(NSMutableArray *)array
888
889ARRAY_ADDER(NSString) {
890  if (array.count > 5) {              // AVOID -- where is 'array' defined?
891    ...
892  }
893}
894```
895
896Examples of acceptable macro use include assertion and debug logging macros
897that are conditionally compiled based on build settings—often, these are
898not compiled into release builds.
899
900### Nonstandard Extensions
901
902Nonstandard extensions to C/Objective-C may not be used unless otherwise
903specified.
904
905Compilers support various extensions that are not part of standard C. Examples
906include compound statement expressions (e.g. `foo = ({ int x; Bar(&x); x })`).
907
908`__attribute__` is an approved exception, as it is used in Objective-C API
909specifications.
910
911The binary form of the conditional operator, `A ?: B`, is an approved exception.
912
913## Cocoa and Objective-C Features
914
915### Identify Designated Initializer
916
917Clearly identify your designated initializer.
918
919It is important for those who might be subclassing your class that the
920designated initializer be clearly identified. That way, they only need to
921override a single initializer (of potentially several) to guarantee the
922initializer of their subclass is called. It also helps those debugging your
923class in the future understand the flow of initialization code if they need to
924step through it. Identify the designated initializer using comments or the
925`NS_DESIGNATED_INITIALIZER` macro. If you use `NS_DESIGNATED_INITIALIZER`, mark
926unsupported initializers with `NS_UNAVAILABLE`.
927
928### Override Designated Initializer
929
930When writing a subclass that requires an `init...` method, make sure you
931override the designated initializer of the superclass.
932
933If you fail to override the designated initializer of the superclass, your
934initializer may not be called in all cases, leading to subtle and very difficult
935to find bugs.
936
937### Overridden NSObject Method Placement
938
939Put overridden methods of NSObject at the top of an `@implementation`.
940
941This commonly applies to (but is not limited to) the `init...`, `copyWithZone:`,
942and `dealloc` methods. The `init...` methods should be grouped together,
943followed by other typical `NSObject` methods such as `description`, `isEqual:`,
944and `hash`.
945
946Convenience class factory methods for creating instances may precede the
947`NSObject` methods.
948
949### Initialization
950
951Don't initialize instance variables to `0` or `nil` in the `init` method; doing
952so is redundant.
953
954All instance variables for a newly allocated object are [initialized
955to](https://developer.apple.com/library/mac/documentation/General/Conceptual/CocoaEncyclopedia/ObjectAllocation/ObjectAllocation.html)
956`0` (except for isa), so don't clutter up the init method by re-initializing
957variables to `0` or `nil`.
958
959### Instance Variables In Headers Should Be @protected or @private
960
961Instance variables should typically be declared in implementation files or
962auto-synthesized by properties. When ivars are declared in a header file, they
963should be marked `@protected` or `@private`.
964
965```objectivec
966// GOOD:
967
968@interface MyClass : NSObject {
969 @protected
970  id _myInstanceVariable;
971}
972@end
973```
974
975### Do Not Use +new
976
977Do not invoke the `NSObject` class method `new`, nor override it in a subclass.
978`+new` is rarely used and contrasts greatly with initializer usage. Instead, use
979`+alloc` and `-init` methods to instantiate retained objects.
980
981### Keep the Public API Simple
982
983Keep your class simple; avoid "kitchen-sink" APIs. If a method doesn't need to
984be public, keep it out of the public interface.
985
986Unlike C++, Objective-C doesn't differentiate between public and private
987methods; any message may be sent to an object. As a result, avoid placing
988methods in the public API unless they are actually expected to be used by a
989consumer of the class. This helps reduce the likelihood they'll be called when
990you're not expecting it. This includes methods that are being overridden from
991the parent class.
992
993Since internal methods are not really private, it's easy to accidentally
994override a superclass's "private" method, thus making a very difficult bug to
995squash. In general, private methods should have a fairly unique name that will
996prevent subclasses from unintentionally overriding them.
997
998### #import and #include
999
1000`#import` Objective-C and Objective-C++ headers, and `#include` C/C++ headers.
1001
1002C/C++ headers include other C/C++ headers using `#include`. Using `#import`
1003on C/C++ headers prevents future inclusions using `#include` and could result in
1004unintended compilation behavior.
1005C/C++ headers should provide their own `#define` guard.
1006
1007### Order of Includes
1008
1009The standard order for header inclusion is the related header, operating system
1010headers, language library headers, and finally groups of headers for other
1011dependencies.
1012
1013The related header precedes others to ensure it has no hidden dependencies.
1014For implementation files the related header is the header file.
1015For test files the related header is the header containing the tested interface.
1016
1017A blank line may separate logically distinct groups of included headers.
1018
1019Within each group the includes should be ordered alphabetically.
1020
1021Import headers using their path relative to the project's source directory.
1022
1023```objectivec
1024// GOOD:
1025
1026#import "ProjectX/BazViewController.h"
1027
1028#import <Foundation/Foundation.h>
1029
1030#include <unistd.h>
1031#include <vector>
1032
1033#include "base/basictypes.h"
1034#include "base/integral_types.h"
1035#include "util/math/mathutil.h"
1036
1037#import "ProjectX/BazModel.h"
1038#import "Shared/Util/Foo.h"
1039```
1040
1041### Use Umbrella Headers for System Frameworks
1042
1043Import umbrella headers for system frameworks and system libraries rather than
1044include individual files.
1045
1046While it may seem tempting to include individual system headers from a framework
1047such as Cocoa or Foundation, in fact it's less work on the compiler if you
1048include the top-level root framework. The root framework is generally
1049pre-compiled and can be loaded much more quickly. In addition, remember to use
1050`@import` or `#import` rather than `#include` for Objective-C frameworks.
1051
1052```objectivec
1053// GOOD:
1054
1055@import UIKit;     // GOOD.
1056#import <Foundation/Foundation.h>     // GOOD.
1057```
1058
1059```objectivec
1060// AVOID:
1061
1062#import <Foundation/NSArray.h>        // AVOID.
1063#import <Foundation/NSString.h>
1064...
1065```
1066
1067### Avoid Messaging the Current Object Within Initializers and `-dealloc`
1068
1069Code in initializers and `-dealloc` should avoid invoking instance methods.
1070
1071Superclass initialization completes before subclass initialization. Until all
1072classes have had a chance to initialize their instance state any method
1073invocation on self may lead to a subclass operating on uninitialized instance
1074state.
1075
1076A similar issue exists for `-dealloc`, where a method invocation may cause a
1077class to operate on state that has been deallocated.
1078
1079One case where this is less obvious is property accessors. These can be
1080overridden just like any other selector. Whenever practical, directly assign to
1081and release ivars in initializers and `-dealloc`, rather than rely on accessors.
1082
1083```objectivec
1084// GOOD:
1085
1086- (instancetype)init {
1087  self = [super init];
1088  if (self) {
1089    _bar = 23;  // GOOD.
1090  }
1091  return self;
1092}
1093```
1094
1095Beware of factoring common initialization code into helper methods:
1096
1097-   Methods can be overridden in subclasses, either deliberately, or
1098    accidentally due to naming collisions.
1099-   When editing a helper method, it may not be obvious that the code is being
1100    run from an initializer.
1101
1102```objectivec
1103// AVOID:
1104
1105- (instancetype)init {
1106  self = [super init];
1107  if (self) {
1108    self.bar = 23;  // AVOID.
1109    [self sharedMethod];  // AVOID. Fragile to subclassing or future extension.
1110  }
1111  return self;
1112}
1113```
1114
1115```objectivec
1116// GOOD:
1117
1118- (void)dealloc {
1119  [_notifier removeObserver:self];  // GOOD.
1120}
1121```
1122
1123```objectivec
1124// AVOID:
1125
1126- (void)dealloc {
1127  [self removeNotifications];  // AVOID.
1128}
1129```
1130
1131### Setters copy NSStrings
1132
1133Setters taking an `NSString` should always copy the string it accepts. This is
1134often also appropriate for collections like `NSArray` and `NSDictionary`.
1135
1136Never just retain the string, as it may be a `NSMutableString`. This avoids the
1137caller changing it under you without your knowledge.
1138
1139Code receiving and holding collection objects should also consider that the
1140passed collection may be mutable, and thus the collection could be more safely
1141held as a copy or mutable copy of the original.
1142
1143```objectivec
1144// GOOD:
1145
1146@property(nonatomic, copy) NSString *name;
1147
1148- (void)setZigfoos:(NSArray<Zigfoo *> *)zigfoos {
1149  // Ensure that we're holding an immutable collection.
1150  _zigfoos = [zigfoos copy];
1151}
1152```
1153
1154### Use Lightweight Generics to Document Contained Types
1155
1156All projects compiling on Xcode 7 or newer versions should make use of the
1157Objective-C lightweight generics notation to type contained objects.
1158
1159Every `NSArray`, `NSDictionary`, or `NSSet` reference should be declared using
1160lightweight generics for improved type safety and to explicitly document usage.
1161
1162```objectivec
1163// GOOD:
1164
1165@property(nonatomic, copy) NSArray<Location *> *locations;
1166@property(nonatomic, copy, readonly) NSSet<NSString *> *identifiers;
1167
1168NSMutableArray<MyLocation *> *mutableLocations = [otherObject.locations mutableCopy];
1169```
1170
1171If the fully-annotated types become complex, consider using a typedef to
1172preserve readability.
1173
1174```objectivec
1175// GOOD:
1176
1177typedef NSSet<NSDictionary<NSString *, NSDate *> *> TimeZoneMappingSet;
1178TimeZoneMappingSet *timeZoneMappings = [TimeZoneMappingSet setWithObjects:...];
1179```
1180
1181Use the most descriptive common superclass or protocol available. In the most
1182generic case when nothing else is known, declare the collection to be explicitly
1183heterogenous using id.
1184
1185```objectivec
1186// GOOD:
1187
1188@property(nonatomic, copy) NSArray<id> *unknowns;
1189```
1190
1191### Avoid Throwing Exceptions
1192
1193Don't `@throw` Objective-C exceptions, but you should be prepared to catch them
1194from third-party or OS calls.
1195
1196This follows the recommendation to use error objects for error delivery in
1197[Apple's Introduction to Exception Programming Topics for
1198Cocoa](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Exceptions/Exceptions.html).
1199
1200We do compile with `-fobjc-exceptions` (mainly so we get `@synchronized`), but
1201we don't `@throw`. Use of `@try`, `@catch`, and `@finally` are allowed when
1202required to properly use 3rd party code or libraries. If you do use them, please
1203document exactly which methods you expect to throw.
1204
1205### `nil` Checks
1206
1207Avoid `nil` pointer checks that exist only to prevent sending messages to `nil`.
1208Sending a message to `nil` [reliably
1209returns](http://www.sealiesoftware.com/blog/archive/2012/2/29/objc_explain_return_value_of_message_to_nil.html)
1210`nil` as a pointer, zero as an integer or floating-point value, structs
1211initialized to `0`, and `_Complex` values equal to `{0, 0}`.
1212
1213```objectivec
1214// AVOID:
1215
1216if (dataSource) {  // AVOID.
1217  [dataSource moveItemAtIndex:1 toIndex:0];
1218}
1219```
1220
1221```objectivec
1222// GOOD:
1223
1224[dataSource moveItemAtIndex:1 toIndex:0];  // GOOD.
1225```
1226
1227Note that this applies to `nil` as a message target, not as a parameter value.
1228Individual methods may or may not safely handle `nil` parameter values.
1229
1230Note too that this is distinct from checking C/C++ pointers and block pointers
1231against `NULL`, which the runtime does not handle and will cause your
1232application to crash. You still need to make sure you do not dereference a
1233`NULL` pointer.
1234
1235### Nullability
1236
1237Interfaces can be decorated with nullability annotations to describe how the
1238interface should be used and how it behaves. Use of nullability regions (e.g.,
1239`NS_ASSUME_NONNULL_BEGIN` and `NS_ASSUME_NONNULL_END`) and explicit nullability
1240annotations are both accepted. Prefer using the `_Nullable` and `_Nonnull`
1241keywords over the `__nullable` and `__nonnull` keywords. For Objective-C methods
1242and properties prefer using the context-sensitive, non-underscored keywords,
1243e.g., `nonnull` and `nullable`.
1244
1245```objectivec
1246// GOOD:
1247
1248/** A class representing an owned book. */
1249@interface GTMBook : NSObject
1250
1251/** The title of the book. */
1252@property(readonly, copy, nonnull) NSString *title;
1253
1254/** The author of the book, if one exists. */
1255@property(readonly, copy, nullable) NSString *author;
1256
1257/** The owner of the book. Setting nil resets to the default owner. */
1258@property(copy, null_resettable) NSString *owner;
1259
1260/** Initializes a book with a title and an optional author. */
1261- (nonnull instancetype)initWithTitle:(nonnull NSString *)title
1262                               author:(nullable NSString *)author
1263    NS_DESIGNATED_INITIALIZER;
1264
1265/** Returns nil because a book is expected to have a title. */
1266- (nullable instancetype)init;
1267
1268@end
1269
1270/** Loads books from the file specified by the given path. */
1271NSArray<GTMBook *> *_Nullable GTMLoadBooksFromFile(NSString *_Nonnull path);
1272```
1273
1274```objectivec
1275// AVOID:
1276
1277NSArray<GTMBook *> *__nullable GTMLoadBooksFromTitle(NSString *__nonnull path);
1278```
1279
1280Be careful assuming that a pointer is not null based on a non-null qualifier
1281because the compiler may not guarantee that the pointer is not null.
1282
1283### BOOL Pitfalls
1284
1285Be careful when converting general integral values to `BOOL`. Avoid comparing
1286directly with `YES`.
1287
1288`BOOL` in OS X and in 32-bit iOS builds is defined as a signed `char`, so it may
1289have values other than `YES` (`1`) and `NO` (`0`). Do not cast or convert
1290general integral values directly to `BOOL`.
1291
1292Common mistakes include casting or converting an array's size, a pointer value,
1293or the result of a bitwise logic operation to a `BOOL` that could, depending on
1294the value of the last byte of the integer value, still result in a `NO` value.
1295When converting a general integral value to a `BOOL`, use ternary operators to
1296return a `YES` or `NO` value.
1297
1298You can safely interchange and convert `BOOL`, `_Bool` and `bool` (see C++ Std
12994.7.4, 4.12 and C99 Std 6.3.1.2). Use `BOOL` in Objective-C method signatures.
1300
1301Using logical operators (`&&`, `||` and `!`) with `BOOL` is also valid and will
1302return values that can be safely converted to `BOOL` without the need for a
1303ternary operator.
1304
1305```objectivec
1306// AVOID:
1307
1308- (BOOL)isBold {
1309  return [self fontTraits] & NSFontBoldTrait;  // AVOID.
1310}
1311- (BOOL)isValid {
1312  return [self stringValue];  // AVOID.
1313}
1314```
1315
1316```objectivec
1317// GOOD:
1318
1319- (BOOL)isBold {
1320  return ([self fontTraits] & NSFontBoldTrait) ? YES : NO;
1321}
1322- (BOOL)isValid {
1323  return [self stringValue] != nil;
1324}
1325- (BOOL)isEnabled {
1326  return [self isValid] && [self isBold];
1327}
1328```
1329
1330Also, don't directly compare `BOOL` variables directly with `YES`. Not only is
1331it harder to read for those well-versed in C, but the first point above
1332demonstrates that return values may not always be what you expect.
1333
1334```objectivec
1335// AVOID:
1336
1337BOOL great = [foo isGreat];
1338if (great == YES) {  // AVOID.
1339  // ...be great!
1340}
1341```
1342
1343```objectivec
1344// GOOD:
1345
1346BOOL great = [foo isGreat];
1347if (great) {         // GOOD.
1348  // ...be great!
1349}
1350```
1351
1352### Interfaces Without Instance Variables
1353
1354Omit the empty set of braces on interfaces that do not declare any instance
1355variables.
1356
1357```objectivec
1358// GOOD:
1359
1360@interface MyClass : NSObject
1361// Does a lot of stuff.
1362- (void)fooBarBam;
1363@end
1364```
1365
1366```objectivec
1367// AVOID:
1368
1369@interface MyClass : NSObject {
1370}
1371// Does a lot of stuff.
1372- (void)fooBarBam;
1373@end
1374```
1375
1376## Cocoa Patterns
1377
1378### Delegate Pattern
1379
1380Delegates, target objects, and block pointers should not be retained when doing
1381so would create a retain cycle.
1382
1383To avoid causing a retain cycle, a delegate or target pointer should be released
1384as soon as it is clear there will no longer be a need to message the object.
1385
1386If there is no clear time at which the delegate or target pointer is no longer
1387needed, the pointer should only be retained weakly.
1388
1389Block pointers cannot be retained weakly. To avoid causing retain cycles in the
1390client code, block pointers should be used for callbacks only where they can be
1391explicitly released after they have been called or once they are no longer
1392needed. Otherwise, callbacks should be done via weak delegate or target
1393pointers.
1394
1395## Objective-C++
1396
1397### Style Matches the Language
1398
1399Within an Objective-C++ source file, follow the style for the language of the
1400function or method you're implementing. In order to minimize clashes between the
1401differing naming styles when mixing Cocoa/Objective-C and C++, follow the style
1402of the method being implemented.
1403
1404For code in an `@implementation` block, use the Objective-C naming rules. For
1405code in a method of a C++ class, use the C++ naming rules.
1406
1407For code in an Objective-C++ file outside of a class implementation, be
1408consistent within the file.
1409
1410```objectivec++
1411// GOOD:
1412
1413// file: cross_platform_header.h
1414
1415class CrossPlatformAPI {
1416 public:
1417  ...
1418  int DoSomethingPlatformSpecific();  // impl on each platform
1419 private:
1420  int an_instance_var_;
1421};
1422
1423// file: mac_implementation.mm
1424#include "cross_platform_header.h"
1425
1426/** A typical Objective-C class, using Objective-C naming. */
1427@interface MyDelegate : NSObject {
1428 @private
1429  int _instanceVar;
1430  CrossPlatformAPI* _backEndObject;
1431}
1432
1433- (void)respondToSomething:(id)something;
1434
1435@end
1436
1437@implementation MyDelegate
1438
1439- (void)respondToSomething:(id)something {
1440  // bridge from Cocoa through our C++ backend
1441  _instanceVar = _backEndObject->DoSomethingPlatformSpecific();
1442  NSString* tempString = [NSString stringWithFormat:@"%d", _instanceVar];
1443  NSLog(@"%@", tempString);
1444}
1445
1446@end
1447
1448/** The platform-specific implementation of the C++ class, using C++ naming. */
1449int CrossPlatformAPI::DoSomethingPlatformSpecific() {
1450  NSString* temp_string = [NSString stringWithFormat:@"%d", an_instance_var_];
1451  NSLog(@"%@", temp_string);
1452  return [temp_string intValue];
1453}
1454```
1455
1456Projects may opt to use an 80 column line length limit for consistency with
1457Google's C++ style guide.
1458
1459## Spacing and Formatting
1460
1461### Spaces vs. Tabs
1462
1463Use only spaces, and indent 2 spaces at a time. We use spaces for indentation.
1464Do not use tabs in your code.
1465
1466You should set your editor to emit spaces when you hit the tab key, and to trim
1467trailing spaces on lines.
1468
1469### Line Length
1470
1471The maximum line length for Objective-C files is 100 columns.
1472
1473You can make violations easier to spot by enabling *Preferences > Text Editing >
1474Page guide at column: 100* in Xcode.
1475
1476### Method Declarations and Definitions
1477
1478One space should be used between the `-` or `+` and the return type, and no
1479spacing in the parameter list except between parameters.
1480
1481Methods should look like this:
1482
1483```objectivec
1484// GOOD:
1485
1486- (void)doSomethingWithString:(NSString *)theString {
1487  ...
1488}
1489```
1490
1491The spacing before the asterisk is optional. When adding new code, be consistent
1492with the surrounding file's style.
1493
1494If a method declaration does not fit on a single line, put each parameter on its
1495own line. All lines except the first should be indented at least four spaces.
1496Colons before parameters should be aligned on all lines. If the colon before the
1497parameter on the first line of a method declaration is positioned such that
1498colon alignment would cause indentation on a subsequent line to be less than
1499four spaces, then colon alignment is only required for all lines except the
1500first.
1501
1502```objectivec
1503// GOOD:
1504
1505- (void)doSomethingWithFoo:(GTMFoo *)theFoo
1506                      rect:(NSRect)theRect
1507                  interval:(float)theInterval {
1508  ...
1509}
1510
1511- (void)shortKeyword:(GTMFoo *)theFoo
1512            longerKeyword:(NSRect)theRect
1513    someEvenLongerKeyword:(float)theInterval
1514                    error:(NSError **)theError {
1515  ...
1516}
1517
1518- (id<UIAdaptivePresentationControllerDelegate>)
1519    adaptivePresentationControllerDelegateForViewController:(UIViewController *)viewController;
1520
1521- (void)presentWithAdaptivePresentationControllerDelegate:
1522    (id<UIAdaptivePresentationControllerDelegate>)delegate;
1523```
1524
1525### Function Declarations and Definitions
1526
1527Prefer putting the return type on the same line as the function name and append
1528all parameters on the same line if they will fit. Wrap parameter lists which do
1529not fit on a single line as you would wrap arguments in a [function
1530call](#Function_Calls).
1531
1532```objectivec
1533// GOOD:
1534
1535NSString *GTMVersionString(int majorVersion, minorVersion) {
1536  ...
1537}
1538
1539void GTMSerializeDictionaryToFileOnDispatchQueue(
1540    NSDictionary<NSString *, NSString *> *dictionary,
1541    NSString *filename,
1542    dispatch_queue_t queue) {
1543  ...
1544}
1545```
1546
1547Function declarations and definitions should also satisfy the following
1548conditions:
1549
1550*   The opening parenthesis must always be on the same line as the function
1551    name.
1552*   If you cannot fit the return type and the function name on a single line,
1553    break between them and do not indent the function name.
1554*   There should never be a space before the opening parenthesis.
1555*   There should never be a space between function parentheses and parameters.
1556*   The open curly brace is always on the end of the last line of the function
1557    declaration, not the start of the next line.
1558*   The close curly brace is either on the last line by itself or on the same
1559    line as the open curly brace.
1560*   There should be a space between the close parenthesis and the open curly
1561    brace.
1562*   All parameters should be aligned if possible.
1563*   Function scopes should be indented 2 spaces.
1564*   Wrapped parameters should have a 4 space indent.
1565
1566### Conditionals
1567
1568Include a space after `if`, `while`, `for`, and `switch`, and around comparison
1569operators.
1570
1571```objectivec
1572// GOOD:
1573
1574for (int i = 0; i < 5; ++i) {
1575}
1576
1577while (test) {};
1578```
1579
1580Braces may be omitted when a loop body or conditional statement fits on a single
1581line.
1582
1583```objectivec
1584// GOOD:
1585
1586if (hasSillyName) LaughOutLoud();
1587
1588for (int i = 0; i < 10; i++) {
1589  BlowTheHorn();
1590}
1591```
1592
1593```objectivec
1594// AVOID:
1595
1596if (hasSillyName)
1597  LaughOutLoud();               // AVOID.
1598
1599for (int i = 0; i < 10; i++)
1600  BlowTheHorn();                // AVOID.
1601```
1602
1603If an `if` clause has an `else` clause, both clauses should use braces.
1604
1605```objectivec
1606// GOOD:
1607
1608if (hasBaz) {
1609  foo();
1610} else {  // The else goes on the same line as the closing brace.
1611  bar();
1612}
1613```
1614
1615```objectivec
1616// AVOID:
1617
1618if (hasBaz) foo();
1619else bar();        // AVOID.
1620
1621if (hasBaz) {
1622  foo();
1623} else bar();      // AVOID.
1624```
1625
1626Intentional fall-through to the next case should be documented with a comment
1627unless the case has no intervening code before the next case.
1628
1629```objectivec
1630// GOOD:
1631
1632switch (i) {
1633  case 1:
1634    ...
1635    break;
1636  case 2:
1637    j++;
1638    // Falls through.
1639  case 3: {
1640    int k;
1641    ...
1642    break;
1643  }
1644  case 4:
1645  case 5:
1646  case 6: break;
1647}
1648```
1649
1650### Expressions
1651
1652Use a space around binary operators and assignments. Omit a space for a unary
1653operator. Do not add spaces inside parentheses.
1654
1655```objectivec
1656// GOOD:
1657
1658x = 0;
1659v = w * x + y / z;
1660v = -y * (x + z);
1661```
1662
1663Factors in an expression may omit spaces.
1664
1665```objectivec
1666// GOOD:
1667
1668v = w*x + y/z;
1669```
1670
1671### Method Invocations
1672
1673Method invocations should be formatted much like method declarations.
1674
1675When there's a choice of formatting styles, follow the convention already used
1676in a given source file. Invocations should have all arguments on one line:
1677
1678```objectivec
1679// GOOD:
1680
1681[myObject doFooWith:arg1 name:arg2 error:arg3];
1682```
1683
1684or have one argument per line, with colons aligned:
1685
1686```objectivec
1687// GOOD:
1688
1689[myObject doFooWith:arg1
1690               name:arg2
1691              error:arg3];
1692```
1693
1694Don't use any of these styles:
1695
1696```objectivec
1697// AVOID:
1698
1699[myObject doFooWith:arg1 name:arg2  // some lines with >1 arg
1700              error:arg3];
1701
1702[myObject doFooWith:arg1
1703               name:arg2 error:arg3];
1704
1705[myObject doFooWith:arg1
1706          name:arg2  // aligning keywords instead of colons
1707          error:arg3];
1708```
1709
1710As with declarations and definitions, when the first keyword is shorter than the
1711others, indent the later lines by at least four spaces, maintaining colon
1712alignment:
1713
1714```objectivec
1715// GOOD:
1716
1717[myObj short:arg1
1718          longKeyword:arg2
1719    evenLongerKeyword:arg3
1720                error:arg4];
1721```
1722
1723Invocations containing multiple inlined blocks may have their parameter names
1724left-aligned at a four space indent.
1725
1726### Function Calls
1727
1728Function calls should include as many parameters as fit on each line, except
1729where shorter lines are needed for clarity or documentation of the parameters.
1730
1731Continuation lines for function parameters may be indented to align with the
1732opening parenthesis, or may have a four-space indent.
1733
1734```objectivec
1735// GOOD:
1736
1737CFArrayRef array = CFArrayCreate(kCFAllocatorDefault, objects, numberOfObjects,
1738                                 &kCFTypeArrayCallBacks);
1739
1740NSString *string = NSLocalizedStringWithDefaultValue(@"FEET", @"DistanceTable",
1741    resourceBundle,  @"%@ feet", @"Distance for multiple feet");
1742
1743UpdateTally(scores[x] * y + bases[x],  // Score heuristic.
1744            x, y, z);
1745
1746TransformImage(image,
1747               x1, x2, x3,
1748               y1, y2, y3,
1749               z1, z2, z3);
1750```
1751
1752Use local variables with descriptive names to shorten function calls and reduce
1753nesting of calls.
1754
1755```objectivec
1756// GOOD:
1757
1758double scoreHeuristic = scores[x] * y + bases[x];
1759UpdateTally(scoreHeuristic, x, y, z);
1760```
1761
1762### Exceptions
1763
1764Format exceptions with `@catch` and `@finally` labels on the same line as the
1765preceding `}`. Add a space between the `@` label and the opening brace (`{`), as
1766well as between the `@catch` and the caught object declaration. If you must use
1767Objective-C exceptions, format them as follows. However, see [Avoid Throwing
1768Exceptions](#Avoid_Throwing_Exceptions) for reasons why you should not be using
1769exceptions.
1770
1771```objectivec
1772// GOOD:
1773
1774@try {
1775  foo();
1776} @catch (NSException *ex) {
1777  bar(ex);
1778} @finally {
1779  baz();
1780}
1781```
1782
1783### Function Length
1784
1785Prefer small and focused functions.
1786
1787Long functions and methods are occasionally appropriate, so no hard limit is
1788placed on function length. If a function exceeds about 40 lines, think about
1789whether it can be broken up without harming the structure of the program.
1790
1791Even if your long function works perfectly now, someone modifying it in a few
1792months may add new behavior. This could result in bugs that are hard to find.
1793Keeping your functions short and simple makes it easier for other people to read
1794and modify your code.
1795
1796When updating legacy code, consider also breaking long functions into smaller
1797and more manageable pieces.
1798
1799### Vertical Whitespace
1800
1801Use vertical whitespace sparingly.
1802
1803To allow more code to be easily viewed on a screen, avoid putting blank lines
1804just inside the braces of functions.
1805
1806Limit blank lines to one or two between functions and between logical groups of
1807code.
1808
1809## Objective-C Style Exceptions
1810
1811### Indicating style exceptions
1812
1813Lines of code that are not expected to adhere to these style recommendations
1814require `// NOLINT` at the end of the line or `// NOLINTNEXTLINE` at the end of
1815the previous line. Sometimes it is required that parts of Objective-C code must
1816ignore these style recommendations (for example code may be machine generated or
1817code constructs are such that its not possible to style correctly).
1818
1819A `// NOLINT` comment on that line or `// NOLINTNEXTLINE` on the previous line
1820can be used to indicate to the reader that code is intentionally ignoring style
1821guidelines. In addition these annotations can also be picked up by automated
1822tools such as linters and handle code correctly. Note that there is a single
1823space between `//` and `NOLINT*`.
1824