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