readability-cli 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
guides/objcguide.md ADDED
@@ -0,0 +1,2386 @@
1
+ # Google Objective-C Style Guide
2
+
3
+ > Objective-C is a dynamic, object-oriented extension of C. It's designed to be
4
+ > easy to use and read, while enabling sophisticated object-oriented design. It
5
+ > is one of the primary development languages for applications on Apple
6
+ > platforms.
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
+ > The purpose of this document is to describe the Objective-C (and
13
+ > Objective-C++) coding guidelines and practices. These guidelines have evolved
14
+ > and been proven over time on other projects and teams.
15
+ > Open-source projects developed by Google conform to the requirements in this guide.
16
+ >
17
+ > Note that this guide is not an Objective-C tutorial. We assume that the reader
18
+ > is familiar with the language. If you are new to Objective-C or need a
19
+ > refresher, please read [Programming with
20
+ > Objective-C](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html).
21
+
22
+
23
+
24
+ ## Principles
25
+
26
+ ### Optimize for the reader, not the writer
27
+
28
+ Codebases often have extended lifetimes and more time is spent reading the code
29
+ than writing it. We explicitly choose to optimize for the experience of our
30
+ average software engineer reading, maintaining, and debugging code in our
31
+ codebase rather than the ease of writing said code. For example, when something
32
+ surprising or unusual is happening in a snippet of code, leaving textual hints
33
+ for the reader is valuable.
34
+
35
+ ### Be consistent
36
+
37
+ When the style guide allows multiple options it is preferable to pick one option
38
+ over mixed usage of multiple options. Using one style consistently throughout a
39
+ codebase lets engineers focus on other (more important) issues. Consistency also
40
+ enables better automation because consistent code allows more efficient
41
+ development and operation of tools that format or refactor code. In many cases,
42
+ rules that are attributed to "Be Consistent" boil down to "Just pick one and
43
+ stop worrying about it"; the potential value of allowing flexibility on these
44
+ points is outweighed by the cost of having people argue over them.
45
+
46
+ ### Be consistent with Apple SDKs
47
+
48
+ Consistency with the way Apple SDKs use Objective-C has value for the same
49
+ reasons as consistency within our code base. If an Objective-C feature solves a
50
+ problem that's an argument for using it. However, sometimes language features
51
+ and idioms are flawed, or were just designed with assumptions that are not
52
+ universal. In those cases it is appropriate to constrain or ban language
53
+ features or idioms.
54
+
55
+ ### Style rules should pull their weight
56
+
57
+ The benefit of a style rule must be large enough to justify asking engineers to
58
+ remember it. The benefit is measured relative to the codebase we would get
59
+ without the rule, so a rule against a very harmful practice may still have a
60
+ small benefit if people are unlikely to do it anyway. This principle mostly
61
+ explains the rules we don’t have, rather than the rules we do: for example, goto
62
+ contravenes many of the following principles, but is not discussed due to its
63
+ extreme rarity.
64
+
65
+ <a id="Example"></a>
66
+
67
+ ## Example
68
+
69
+ They say an example is worth a thousand words, so let's start off with an
70
+ example that should give you a feel for the style, spacing, naming, and so on.
71
+
72
+ Here is an example header file, demonstrating the correct commenting and spacing
73
+ for an `@interface` declaration.
74
+
75
+ ```objectivec
76
+ // GOOD:
77
+
78
+ #import <Foundation/Foundation.h>
79
+
80
+ @class Bar;
81
+
82
+ /**
83
+ * A sample class demonstrating good Objective-C style. All interfaces,
84
+ * categories, and protocols (read: all non-trivial top-level declarations
85
+ * in a header) MUST be commented. Comments must also be adjacent to the
86
+ * object they're documenting.
87
+ */
88
+ @interface Foo : NSObject
89
+
90
+ /** The retained Bar. */
91
+ @property(nonatomic) Bar *bar;
92
+
93
+ /** The current drawing attributes. */
94
+ @property(nonatomic, copy) NSDictionary<NSString *, NSNumber *> *attributes;
95
+
96
+ /**
97
+ * Convenience creation method.
98
+ * See -initWithBar: for details about @c bar.
99
+ *
100
+ * @param bar The string for fooing.
101
+ * @return An instance of Foo.
102
+ */
103
+ + (instancetype)fooWithBar:(Bar *)bar;
104
+
105
+ /**
106
+ * Initializes and returns a Foo object using the provided Bar instance.
107
+ *
108
+ * @param bar A string that represents a thing that does a thing.
109
+ */
110
+ - (instancetype)initWithBar:(Bar *)bar NS_DESIGNATED_INITIALIZER;
111
+
112
+ /**
113
+ * Does some work with @c blah.
114
+ *
115
+ * @param blah
116
+ * @return YES if the work was completed; NO otherwise.
117
+ */
118
+ - (BOOL)doWorkWithBlah:(NSString *)blah;
119
+
120
+ @end
121
+ ```
122
+
123
+ An example source file, demonstrating the correct commenting and spacing for the
124
+ `@implementation` of an interface.
125
+
126
+ ```objectivec
127
+ // GOOD:
128
+
129
+ #import "Shared/Util/Foo.h"
130
+
131
+ @implementation Foo {
132
+ /** The string used for displaying "hi". */
133
+ NSString *_string;
134
+ }
135
+
136
+ + (instancetype)fooWithBar:(Bar *)bar {
137
+ return [[self alloc] initWithBar:bar];
138
+ }
139
+
140
+ - (instancetype)init {
141
+ // Classes with a custom designated initializer should always override
142
+ // the superclass's designated initializer.
143
+ return [self initWithBar:nil];
144
+ }
145
+
146
+ - (instancetype)initWithBar:(Bar *)bar {
147
+ self = [super init];
148
+ if (self) {
149
+ _bar = [bar copy];
150
+ _string = [[NSString alloc] initWithFormat:@"hi %d", 3];
151
+ _attributes = @{
152
+ @"color" : UIColor.blueColor,
153
+ @"hidden" : @NO
154
+ };
155
+ }
156
+ return self;
157
+ }
158
+
159
+ - (BOOL)doWorkWithBlah:(NSString *)blah {
160
+ // Work should be done here.
161
+ return NO;
162
+ }
163
+
164
+ @end
165
+ ```
166
+
167
+ <a id="Naming"></a>
168
+
169
+ ## Naming
170
+
171
+ Names should be as descriptive as possible, within reason. Follow standard
172
+ [Objective-C naming
173
+ rules](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html).
174
+
175
+ Avoid non-standard abbreviations (including non-standard acronyms and
176
+ initialisms). Don't worry about saving horizontal space as it is far more
177
+ important to make your code immediately understandable by a new reader. For
178
+ example:
179
+
180
+ ```objectivec
181
+ // GOOD:
182
+
183
+ // Good names.
184
+ int numberOfErrors = 0;
185
+ int completedConnectionsCount = 0;
186
+ tickets = [[NSMutableArray alloc] init];
187
+ userInfo = [someObject object];
188
+ port = [network port];
189
+ NSDate *gAppLaunchDate;
190
+ ```
191
+
192
+ ```objectivec
193
+ // AVOID:
194
+
195
+ // Names to avoid.
196
+ int w;
197
+ int nerr;
198
+ int nCompConns;
199
+ tix = [[NSMutableArray alloc] init];
200
+ obj = [someObject object];
201
+ p = [network port];
202
+ ```
203
+
204
+ Any class, category, method, function, or variable name should use all capitals
205
+ for acronyms and [initialisms](https://en.wikipedia.org/wiki/Initialism) within
206
+ (including at the beginning of) the name. This follows Apple's standard of using
207
+ all capitals within a name for acronyms such as URL, ID, TIFF, and EXIF.
208
+
209
+ Names of C functions and typedefs should be capitalized and use camel case as
210
+ appropriate for the surrounding code.
211
+
212
+ <a id="Inclusive_Language"></a>
213
+
214
+ ### Inclusive Language
215
+
216
+ In all code, including naming and comments, use inclusive language and avoid
217
+ terms that other programmers might find disrespectful or offensive (such as
218
+ "master" and "slave", "blacklist" and "whitelist", or "redline"), even if the
219
+ terms also have an ostensibly neutral meaning. Similarly, use gender-neutral
220
+ language unless you're referring to a specific person (and using their
221
+ pronouns). For example, use "they"/"them"/"their" for people of unspecified
222
+ gender (even when singular), and "it"/"its" for non-people.
223
+
224
+
225
+ <a id="File_Names"></a>
226
+
227
+ ### File Names
228
+
229
+ File names should reflect the name of the class implementation that they
230
+ contain—including case.
231
+
232
+ Follow the convention that your project uses.
233
+
234
+ File extensions should be as follows:
235
+
236
+ Extension | Type
237
+ --------- | ---------------------------------
238
+ .h | C/C++/Objective-C header file
239
+ .m | Objective-C implementation file
240
+ .mm | Objective-C++ implementation file
241
+ .cc | Pure C++ implementation file
242
+ .c | C implementation file
243
+
244
+ Files containing code that may be shared across projects or used in a large
245
+ project should have a clearly unique name, typically including the project or
246
+ class [prefix](#prefixes).
247
+
248
+ File names for categories should include the name of the class being extended,
249
+ like GTMNSString+Utils.h or NSTextView+GTMAutocomplete.h
250
+
251
+ ### Prefixes
252
+
253
+ Prefixes are commonly required in Objective-C to avoid naming collisions in a
254
+ global namespace. Classes, protocols, global functions, and global constants
255
+ should generally be named with a prefix that begins with a capital letter
256
+ followed by one or more capital letters or numbers.
257
+
258
+ WARNING: Apple reserves two-letter prefixes—see
259
+ [Conventions in Programming with Objective-C](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Conventions/Conventions.html)—so
260
+ prefixes with a minimum of three characters are considered best practice.
261
+
262
+ ```objectivec
263
+ // GOOD:
264
+
265
+ /** An example error domain. */
266
+ GTM_EXTERN NSString *GTMExampleErrorDomain;
267
+
268
+ /** Gets the default time zone. */
269
+ GTM_EXTERN NSTimeZone *GTMGetDefaultTimeZone(void);
270
+
271
+ /** An example delegate. */
272
+ @protocol GTMExampleDelegate <NSObject>
273
+ @end
274
+
275
+ /** An example class. */
276
+ @interface GTMExample : NSObject
277
+ @end
278
+
279
+ ```
280
+
281
+ <a id="Class_Names"></a>
282
+
283
+ ### Class Names
284
+
285
+ Class names (along with category and protocol names) should start as uppercase
286
+ and use mixed case to delimit words.
287
+
288
+ Classes and protocols in code shared across multiple applications must have an
289
+ appropriate [prefix](#prefixes) (e.g. GTMSendMessage). Prefixes are recommended,
290
+ but not required, for other classes and protocols.
291
+
292
+ <a id="Category_Names"></a>
293
+
294
+ ### Category Naming
295
+
296
+ Category names should start with an appropriate [prefix](#prefixes) identifying
297
+ the category as part of a project or open for general use.
298
+
299
+ Category source file names should begin with the class being extended followed
300
+ by a plus sign and the name of the category, e.g., `NSString+GTMParsing.h`.
301
+ Methods in a category should be prefixed with a lowercase version of the prefix
302
+ used for the category name followed by an underscore (e.g.,
303
+ `gtm_myCategoryMethodOnAString:`) in order to prevent collisions in
304
+ Objective-C's global namespace.
305
+
306
+ There should be a single space between the class name and the opening
307
+ parenthesis of the category.
308
+
309
+ ```objectivec
310
+ // GOOD:
311
+
312
+ // UIViewController+GTMCrashReporting.h
313
+
314
+ /** A category that adds metadata to include in crash reports to UIViewController. */
315
+ @interface UIViewController (GTMCrashReporting)
316
+
317
+ /** A unique identifier to represent the view controller in crash reports. */
318
+ @property(nonatomic, setter=gtm_setUniqueIdentifier:) int gtm_uniqueIdentifier;
319
+
320
+ /** Returns an encoded representation of the view controller's current state. */
321
+ - (nullable NSData *)gtm_encodedState;
322
+
323
+ @end
324
+ ```
325
+
326
+ If a class is not shared with other projects, categories extending it may omit
327
+ name prefixes and method name prefixes.
328
+
329
+ ```objectivec
330
+ // GOOD:
331
+
332
+ /** This category extends a class that is not shared with other projects. */
333
+ @interface XYZDataObject (Storage)
334
+ - (NSString *)storageIdentifier;
335
+ @end
336
+ ```
337
+
338
+ <a id="Objective-C_Method_Names"></a>
339
+
340
+ ### Objective-C Method Names
341
+
342
+ Method and parameter names typically start as lowercase and then use mixed case.
343
+
344
+ Proper capitalization should be respected, including at the beginning of names.
345
+
346
+ ```objectivec
347
+ // GOOD:
348
+
349
+ + (NSURL *)URLWithString:(NSString *)URLString;
350
+ ```
351
+
352
+ The method name should read like a sentence if possible, meaning you should
353
+ choose parameter names that flow with the method name. Objective-C method names
354
+ tend to be very long, but this has the benefit that a block of code can almost
355
+ read like prose, thus rendering many implementation comments unnecessary.
356
+
357
+ Use prepositions and conjunctions like "with", "from", and "to" in the second
358
+ and later parameter names only where necessary to clarify the meaning or
359
+ behavior of the method.
360
+
361
+ ```objectivec
362
+ // GOOD:
363
+
364
+ - (void)addTarget:(id)target action:(SEL)action; // GOOD; no conjunction needed
365
+ - (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view; // GOOD; conjunction clarifies parameter
366
+ - (void)replaceCharactersInRange:(NSRange)aRange
367
+ withAttributedString:(NSAttributedString *)attributedString; // GOOD.
368
+ ```
369
+
370
+ If the method returns an attribute of the receiver, name the method after the
371
+ attribute.
372
+
373
+ ```objectivec
374
+ // GOOD:
375
+
376
+ /** Returns this instance's sandwich. */
377
+ - (Sandwich *)sandwich; // GOOD.
378
+
379
+ - (CGFloat)height; // GOOD.
380
+
381
+ // GOOD; Returned value is not an attribute.
382
+ - (UIBackgroundTaskIdentifier)beginBackgroundTask;
383
+ ```
384
+
385
+ ```objectivec
386
+ // AVOID:
387
+
388
+ - (CGFloat)calculateHeight; // AVOID.
389
+ - (id)theDelegate; // AVOID.
390
+ ```
391
+
392
+ An accessor method should be named the same as the object it's getting, but it
393
+ should not be prefixed with the word `get`. For example:
394
+
395
+ ```objectivec
396
+ // GOOD:
397
+
398
+ - (id)delegate; // GOOD.
399
+ ```
400
+
401
+ ```objectivec
402
+ // AVOID:
403
+
404
+ - (id)getDelegate; // AVOID.
405
+ ```
406
+
407
+ Accessors that return the value of boolean adjectives have method names
408
+ beginning with `is`, but property names for those methods omit the `is`.
409
+
410
+ Dot notation is used only with property names, not with method names.
411
+
412
+ ```objectivec
413
+ // GOOD:
414
+
415
+ @property(nonatomic, getter=isGlorious) BOOL glorious;
416
+ // The method for the getter of the property above is:
417
+ // - (BOOL)isGlorious;
418
+
419
+ BOOL isGood = object.glorious; // GOOD.
420
+ BOOL isGood = [object isGlorious]; // GOOD.
421
+ ```
422
+
423
+ ```objectivec
424
+ // AVOID:
425
+
426
+ BOOL isGood = object.isGlorious; // AVOID.
427
+ ```
428
+
429
+ ```objectivec
430
+ // GOOD:
431
+
432
+ NSArray<Frog *> *frogs = [NSArray<Frog *> arrayWithObject:frog];
433
+ NSEnumerator *enumerator = [frogs reverseObjectEnumerator]; // GOOD.
434
+ ```
435
+
436
+ ```objectivec
437
+ // AVOID:
438
+
439
+ NSEnumerator *enumerator = frogs.reverseObjectEnumerator; // AVOID.
440
+ ```
441
+
442
+ See [Apple's Guide to Naming
443
+ Methods](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282-BCIGIJJF)
444
+ for more details on Objective-C naming.
445
+
446
+ These guidelines are for Objective-C methods only. C++ method names continue to
447
+ follow the rules set in the C++ style guide.
448
+
449
+ <a id="Function_Names"></a>
450
+
451
+ ### Function Names
452
+
453
+ Function names should start with a capital letter and have a capital letter for
454
+ each new word (a.k.a. "[camel case](https://en.wikipedia.org/wiki/Camel_case)"
455
+ or "Pascal case").
456
+
457
+ ```objectivec
458
+ // GOOD:
459
+
460
+ static void AddTableEntry(NSString *tableEntry);
461
+ static BOOL DeleteFile(const char *filename);
462
+ ```
463
+
464
+ Because Objective-C does not provide namespacing, non-static functions should
465
+ have a [prefix](#prefixes) that minimizes the chance of a name collision.
466
+
467
+ ```objectivec
468
+ // GOOD:
469
+
470
+ GTM_EXTERN NSTimeZone *GTMGetDefaultTimeZone(void);
471
+ GTM_EXTERN NSString *GTMGetURLScheme(NSURL *URL);
472
+ ```
473
+
474
+ <a id="Variable_Names"></a>
475
+
476
+ ### Variable Names
477
+
478
+ Variable names typically start with a lowercase and use mixed case to delimit
479
+ words.
480
+
481
+ Instance variables have leading underscores. File scope or global variables have
482
+ a prefix `g`. For example: `myLocalVariable`, `_myInstanceVariable`,
483
+ `gMyGlobalVariable`.
484
+
485
+ <a id="Common_Variable_Names"></a>
486
+
487
+ #### Common Variable Names
488
+
489
+ Readers should be able to infer the variable type from the name, but do not use
490
+ Hungarian notation for syntactic attributes, such as the static type of a
491
+ variable (int or pointer).
492
+
493
+ File scope or global variables (as opposed to constants) declared outside the
494
+ scope of a method or function should be rare, and should have the prefix `g`.
495
+
496
+ ```objectivec
497
+ // GOOD:
498
+
499
+ static int gGlobalCounter;
500
+ ```
501
+
502
+ <a id="Instance_Variables"></a>
503
+
504
+ #### Instance Variables
505
+
506
+ Instance variable names are mixed case and should be prefixed with an
507
+ underscore, like `_usernameTextField`.
508
+
509
+ NOTE: Google's previous convention for Objective-C ivars was a trailing
510
+ underscore. Existing projects may opt to continue using trailing underscores in
511
+ new code in order to maintain consistency within the project codebase.
512
+ Consistency of prefix or suffix underscores should be maintained within each
513
+ class.
514
+
515
+ <a id="Constants"></a>
516
+
517
+ #### Constants
518
+
519
+ Constant symbols (const global and static variables and constants created
520
+ with #define) should use mixed case to delimit words.
521
+
522
+ Global and file scope constants should have an appropriate [prefix](#prefixes).
523
+
524
+ ```objectivec
525
+ // GOOD:
526
+
527
+ /** The domain for GTL service errors. */
528
+ GTL_EXTERN NSString *const GTLServiceErrorDomain;
529
+
530
+ /** An enumeration of GTL service error codes. */
531
+ typedef NS_ENUM(int32_t, GTLServiceError) {
532
+ /** An error code indicating that a query result was missing. */
533
+ GTLServiceErrorQueryResultMissing = -3000,
534
+ /** An error code indicating that the query timed out. */
535
+ GTLServiceErrorQueryTimedOut = -3001,
536
+ };
537
+ ```
538
+
539
+ Because Objective-C does not provide namespacing, constants with external
540
+ linkage should have a prefix that minimizes the chance of a name collision,
541
+ typically like `ClassNameConstantName` or `ClassNameEnumName`.
542
+
543
+ For interoperability with Swift code, enumerated values should have names that
544
+ extend the typedef name:
545
+
546
+ ```objectivec
547
+ // GOOD:
548
+
549
+ /** An enumeration of supported display tinges. */
550
+ typedef NS_ENUM(int32_t, DisplayTinge) {
551
+ DisplayTingeGreen = 1,
552
+ DisplayTingeBlue = 2,
553
+ };
554
+ ```
555
+
556
+ A lowercase k can be used as a standalone prefix for constants of static storage
557
+ duration declared within implementation files:
558
+
559
+ ```objectivec
560
+ // GOOD:
561
+
562
+ static const int kFileCount = 12;
563
+ static NSString *const kUserKey = @"kUserKey";
564
+ ```
565
+
566
+ NOTE: Previous convention was for public constant names to begin with a
567
+ lowercase k followed by a project-specific [prefix](#prefixes). This practice is
568
+ no longer recommended.
569
+
570
+ <a id="Types_and_Declarations"></a>
571
+
572
+ ## Types and Declarations
573
+
574
+ <a id="Method_Declarations"></a>
575
+
576
+ ### Method Declarations
577
+
578
+ As shown in the [example](#Example), the recommended order
579
+ for declarations in an `@interface` declaration are: properties, class methods,
580
+ initializers, and then finally instance methods. The class methods section
581
+ should begin with any convenience constructors.
582
+
583
+ <a id="Local_Variables"></a>
584
+
585
+ ### Local Variables
586
+
587
+ Declare variables in the narrowest practical scopes, and close to their use.
588
+ Initialize variables in their declarations.
589
+
590
+ ```objectivec
591
+ // GOOD:
592
+
593
+ CLLocation *location = [self lastKnownLocation];
594
+ for (int meters = 1; meters < 10; meters++) {
595
+ reportFrogsWithinRadius(location, meters);
596
+ }
597
+ ```
598
+
599
+ Occasionally, efficiency will make it more appropriate to declare a variable
600
+ outside the scope of its use. This example declares meters separate from
601
+ initialization, and needlessly sends the lastKnownLocation message each time
602
+ through the loop:
603
+
604
+ ```objectivec
605
+ // AVOID:
606
+
607
+ int meters; // AVOID.
608
+ for (meters = 1; meters < 10; meters++) {
609
+ CLLocation *location = [self lastKnownLocation]; // AVOID.
610
+ reportFrogsWithinRadius(location, meters);
611
+ }
612
+ ```
613
+
614
+ Under Automatic Reference Counting, strong and weak pointers to Objective-C
615
+ objects are automatically initialized to `nil`, so explicit initialization to
616
+ `nil` is not required for those common cases. However, automatic initialization
617
+ does *not* occur for many Objective-C pointer types, including object pointers
618
+ declared with the `__unsafe_unretained` ownership qualifier and CoreFoundation
619
+ object pointer types. When in doubt, prefer to initialize all Objective-C
620
+ local variables.
621
+
622
+ ### Static Variables
623
+
624
+ When file scope variable/constant declarations in an implementation file do not
625
+ need to be referenced outside that file, declare them static (or in an anonymous
626
+ namespace in Objective-C++). Do not declare file scope variables or constants
627
+ with static storage duration (or in anonymous namespaces in Objective-C++) in .h
628
+ files.
629
+
630
+ ```objectivec
631
+ // GOOD:
632
+
633
+ // file: Foo.m
634
+ static const int FOORequestLimit = 5;
635
+ ```
636
+
637
+ ```objectivec
638
+ // AVOID:
639
+
640
+ // file: Foo.h
641
+ static const int FOORequestLimit = 5; // AVOID.
642
+ ```
643
+
644
+ <a id="Unsigned_Integers"></a>
645
+
646
+ ### Unsigned Integers
647
+
648
+ Avoid unsigned integers except when matching types used by system interfaces.
649
+
650
+ Subtle errors crop up when doing math or counting down to zero using unsigned
651
+ integers. Rely only on signed integers in math expressions except when matching
652
+ NSUInteger in system interfaces.
653
+
654
+ ```objectivec
655
+ // GOOD:
656
+
657
+ NSUInteger numberOfObjects = array.count;
658
+ for (NSInteger counter = numberOfObjects - 1; counter >= 0; --counter)
659
+ ```
660
+
661
+ ```objectivec
662
+ // AVOID:
663
+
664
+ for (NSUInteger counter = numberOfObjects - 1; counter >= 0; --counter) // AVOID.
665
+ ```
666
+
667
+ Unsigned integers may be used for flags and bitmasks, though often NS_OPTIONS or
668
+ NS_ENUM will be more appropriate.
669
+
670
+ <a id="Types_with_Inconsistent_Sizes"></a>
671
+
672
+ ### Types with Inconsistent Sizes
673
+
674
+ Be aware that types long, NSInteger, NSUInteger and CGFloat have sizes that
675
+ differ in 32- and 64-bit builds. Their use is appropriate when matching system
676
+ interfaces but should be avoided when dealing with APIs that
677
+ require exact sizing, e.g., proto APIs.
678
+
679
+ ```objectivec
680
+ // GOOD:
681
+
682
+ int32_t scalar1 = proto.intValue;
683
+
684
+ int64_t scalar2 = proto.longValue;
685
+
686
+ NSUInteger numberOfObjects = array.count;
687
+
688
+ CGFloat offset = view.bounds.origin.x;
689
+ ```
690
+
691
+ ```objectivec
692
+ // AVOID:
693
+
694
+ NSInteger scalar2 = proto.longValue; // AVOID.
695
+ ```
696
+
697
+ File and buffer sizes often exceed 32-bit limits, so they should be declared
698
+ using `int64_t`, not with `long`, `NSInteger`, or `NSUInteger`.
699
+
700
+ <a id="Floating_Point_Constants"></a>
701
+
702
+ #### Floating Point Constants
703
+
704
+ When defining `CGFloat` constants, please keep in mind the following.
705
+
706
+ Previously for projects targeting 32-bit platforms, using `float` literals
707
+ (numbers with the `f` suffix) could be necessary to avoid type-conversion
708
+ warnings.
709
+
710
+ Since all Google iOS projects are now targeting only 64-bit runtime, `CGFloat`
711
+ constants may omit the suffix (use `double` values). However, teams may choose
712
+ to continue using `float` numbers for legacy code consistency, until they
713
+ eventually migrate to `double` values everywhere. Avoid a mixture of `float`
714
+ and `double` values in the same code.
715
+
716
+ ```objectivec
717
+ // GOOD:
718
+
719
+ // Good since CGFloat is double
720
+ static const CGFloat kHorizontalMargin = 8.0;
721
+ static const CGFloat kVerticalMargin = 12.0;
722
+
723
+ // This is OK as long as all values for CGFloat constants in your project are float
724
+ static const CGFloat kHorizontalMargin = 8.0f;
725
+ static const CGFloat kVerticalMargin = 12.0f;
726
+ ```
727
+
728
+ ```objectivec
729
+ // AVOID:
730
+
731
+ // Avoid a mixture of float and double constants
732
+ static const CGFloat kHorizontalMargin = 8.0f;
733
+ static const CGFloat kVerticalMargin = 12.0;
734
+ ```
735
+
736
+ <a id="Comments"></a>
737
+
738
+ ## Comments
739
+
740
+ Comments are absolutely vital to keeping our code readable. The following rules
741
+ describe what you should comment and where. But remember: while comments are
742
+ important, the best code is self-documenting. Giving sensible names to types and
743
+ variables is much better than using obscure names and then trying to explain
744
+ them through comments.
745
+
746
+ Pay attention to punctuation, spelling, and grammar; it is easier to read
747
+ well-written comments than badly written ones.
748
+
749
+ Comments should be as readable as narrative text, with proper capitalization and
750
+ punctuation. In many cases, complete sentences are more readable than sentence
751
+ fragments. Shorter comments, such as comments at the end of a line of code, can
752
+ sometimes be less formal, but use a consistent style.
753
+
754
+ When writing your comments, write for your audience: the next contributor who
755
+ will need to understand your code. Be generous—the next one may be you!
756
+
757
+ <a id="File_Comments"></a>
758
+
759
+ ### File Comments
760
+
761
+ A file may optionally start with a description of its contents.
762
+
763
+ Every file may contain the following items, in order
764
+ * License boilerplate if necessary. Choose the appropriate boilerplate for the
765
+ license used by the project.
766
+ * A basic description of the contents of the file if necessary.
767
+
768
+ If you make significant changes to a file with an author line, consider deleting
769
+ the author line since revision history already provides a more detailed and
770
+ accurate record of authorship.
771
+
772
+
773
+ <a id="Declaration_Comments"></a>
774
+
775
+ ### Declaration Comments
776
+
777
+ Every non-trivial interface, public and private, should have an accompanying
778
+ comment describing its purpose and how it fits into the larger picture.
779
+
780
+ Comments should be used to document classes, properties, ivars, functions,
781
+ categories, protocol declarations, and enums.
782
+
783
+
784
+ ```objectivec
785
+ // GOOD:
786
+
787
+ /**
788
+ * A delegate for NSApplication to handle notifications about app
789
+ * launch and shutdown. Owned by the main app controller.
790
+ */
791
+ @interface MyAppDelegate : NSObject {
792
+ /**
793
+ * The background task in progress, if any. This is initialized
794
+ * to the value UIBackgroundTaskInvalid.
795
+ */
796
+ UIBackgroundTaskIdentifier _backgroundTaskID;
797
+ }
798
+
799
+ /** The factory that creates and manages fetchers for the app. */
800
+ @property(nonatomic) GTMSessionFetcherService *fetcherService;
801
+
802
+ @end
803
+ ```
804
+
805
+ [Doxygen](https://doxygen.nl)-style comments are encouraged for interfaces as
806
+ they are parsed by Xcode
807
+ to display formatted documentation. There is a wide variety of
808
+ [Doxygen commands](https://www.doxygen.nl/manual/commands.html);
809
+ use them consistently within a project.
810
+
811
+ If you have already described an interface in detail in the comments at the top
812
+ of your file, feel free to simply state, "See comment at top of file for a
813
+ complete description", but be sure to have some sort of comment.
814
+
815
+ Additionally, each method should have a comment explaining its function,
816
+ arguments, return value, thread or queue assumptions, and any side effects.
817
+ Documentation comments should be in the header for public methods, or
818
+ immediately preceding the method for non-trivial private methods.
819
+
820
+ Use descriptive form ("Opens the file") rather than imperative form ("Open the
821
+ file") for method and function comments. The comment describes the function; it
822
+ does not tell the function what to do.
823
+
824
+ Document the thread usage assumptions the class, properties, or methods make, if
825
+ any. If an instance of the class can be accessed by multiple threads, take extra
826
+ care to document the rules and invariants surrounding multithreaded use.
827
+
828
+ Any sentinel values for properties and ivars, such as `NULL` or `-1`, should be
829
+ documented in comments.
830
+
831
+ Declaration comments explain how a method or function is used. Comments
832
+ explaining how a method or function is implemented should be with the
833
+ implementation rather than with the declaration.
834
+
835
+ Declaration comments may be omitted on test case classes and test methods
836
+ if comments would communicate no additional information beyond the method's
837
+ name. Utility methods in tests or test-specific classes (such as helpers) should
838
+ be commented.
839
+
840
+ <a id="Implementation_Comments"></a>
841
+
842
+ ### Implementation Comments
843
+
844
+ Provide comments explaining tricky, subtle, or complicated sections of code.
845
+
846
+ ```objectivec
847
+ // GOOD:
848
+
849
+ // Set the property to nil before invoking the completion handler to
850
+ // avoid the risk of reentrancy leading to the callback being
851
+ // invoked again.
852
+ CompletionHandler handler = self.completionHandler;
853
+ self.completionHandler = nil;
854
+ handler();
855
+ ```
856
+
857
+ When useful, also provide comments about implementation approaches that were
858
+ considered or abandoned.
859
+
860
+ End-of-line comments should be separated from the code by at least 2 spaces. If
861
+ you have several comments on subsequent lines, it can often be more readable to
862
+ line them up.
863
+
864
+ ```objectivec
865
+ // GOOD:
866
+
867
+ [self doSomethingWithALongName]; // Two spaces before the comment.
868
+ [self doSomethingShort]; // More spacing to align the comment.
869
+ ```
870
+
871
+
872
+ <a id="Disambiguating_Symbols"></a>
873
+
874
+ ### Disambiguating Symbols
875
+
876
+ Where needed to avoid ambiguity, use backticks or vertical bars to quote
877
+ variable names and symbols in comments in preference to using quotation marks
878
+ or naming the symbols inline.
879
+
880
+ In Doxygen-style comments, prefer demarcating symbols with a monospace text
881
+ command, such as [`@c`](https://www.doxygen.nl/manual/commands.html#cmdc).
882
+
883
+ Demarcation helps provide clarity when a symbol is a common word that might make
884
+ the sentence read like it was poorly constructed. A common example is the symbol
885
+ `count`:
886
+
887
+ ```objectivec
888
+ // GOOD:
889
+
890
+ // Sometimes `count` will be less than zero.
891
+ ```
892
+
893
+ or when quoting something which already contains quotes
894
+
895
+ ```objectivec
896
+ // GOOD:
897
+
898
+ // Remember to call `StringWithoutSpaces("foo bar baz")`
899
+ ```
900
+
901
+ Backticks or vertical bars are not needed when a symbol is self-apparent.
902
+
903
+ ```objectivec
904
+ // GOOD:
905
+
906
+ // This class serves as a delegate to GTMDepthCharge.
907
+ ```
908
+
909
+ Doxygen formatting is also suitable for identifying symbols.
910
+
911
+ ```objectivec
912
+ // GOOD:
913
+
914
+ /** @param maximum The highest value for @c count. */
915
+ ```
916
+
917
+ <a id="Object_Ownership"></a>
918
+
919
+ ### Object Ownership
920
+
921
+ For objects not managed by ARC, make the pointer ownership model as explicit as
922
+ possible when it falls outside the most common Objective-C usage idioms.
923
+
924
+ <a id="Manual_Reference_Counting"></a>
925
+
926
+ #### Manual Reference Counting
927
+
928
+ Instance variables for NSObject-derived objects are presumed to be retained; if
929
+ they are not retained, they should be either commented as weak or declared with
930
+ the `__weak` lifetime qualifier.
931
+
932
+ An exception is in Mac software for instance variables labeled as `@IBOutlets`,
933
+ which are presumed to not be retained.
934
+
935
+ Where instance variables are pointers to Core Foundation, C++, and other
936
+ non-Objective-C objects, they should always be declared with strong and weak
937
+ comments to indicate which pointers are and are not retained. Core Foundation
938
+ and other non-Objective-C object pointers require explicit memory management,
939
+ even when building for automatic reference counting.
940
+
941
+ Examples of strong and weak declarations:
942
+
943
+ ```objectivec
944
+ // GOOD:
945
+
946
+ @interface MyDelegate : NSObject
947
+
948
+ @property(nonatomic) NSString *doohickey;
949
+ @property(nonatomic, weak) NSString *parent;
950
+
951
+ @end
952
+
953
+
954
+ @implementation MyDelegate {
955
+ IBOutlet NSButton *_okButton; // Normal NSControl; implicitly weak on Mac only
956
+
957
+ AnObjcObject *_doohickey; // My doohickey
958
+ __weak MyObjcParent *_parent; // To send messages back (owns this instance)
959
+
960
+ // non-NSObject pointers...
961
+ CWackyCPPClass *_wacky; // Strong, some cross-platform object
962
+ CFDictionaryRef *_dict; // Strong
963
+ }
964
+ @end
965
+ ```
966
+
967
+ <a id="Automatic_Reference_Counting"></a>
968
+
969
+ #### Automatic Reference Counting
970
+
971
+ Object ownership and lifetime are explicit when using ARC, so no additional
972
+ comments are required for automatically retained objects.
973
+
974
+ <a id="C_Language_Features"></a>
975
+
976
+ ## C Language Features
977
+
978
+ <a id="Macros"></a>
979
+
980
+ ### Macros
981
+
982
+ Avoid macros, especially where `const` variables, enums, Xcode snippets, or C
983
+ functions may be used instead.
984
+
985
+ Macros make the code you see different from the code the compiler sees. Modern C
986
+ renders traditional uses of macros for constants and utility functions
987
+ unnecessary. Macros should only be used when there is no other solution
988
+ available.
989
+
990
+ Where a macro is needed, use a unique name to avoid the risk of a symbol
991
+ collision in the compilation unit. If practical, keep the scope limited by
992
+ `#undefining` the macro after its use.
993
+
994
+ Macro names should use `SHOUTY_SNAKE_CASE`—all uppercase letters with
995
+ underscores between words. Function-like macros may use C function naming
996
+ practices. Do not define macros that appear to be C or Objective-C keywords.
997
+
998
+ ```objectivec
999
+ // GOOD:
1000
+
1001
+ #define GTM_EXPERIMENTAL_BUILD ... // GOOD
1002
+
1003
+ // Assert unless X > Y
1004
+ #define GTM_ASSERT_GT(X, Y) ... // GOOD, macro style.
1005
+
1006
+ // Assert unless X > Y
1007
+ #define GTMAssertGreaterThan(X, Y) ... // GOOD, function style.
1008
+ ```
1009
+
1010
+ ```objectivec
1011
+ // AVOID:
1012
+
1013
+ #define kIsExperimentalBuild ... // AVOID
1014
+
1015
+ #define unless(X) if(!(X)) // AVOID
1016
+ ```
1017
+
1018
+ Avoid macros that expand to unbalanced C or Objective-C constructs. Avoid macros
1019
+ that introduce scope, or may obscure the capturing of values in blocks.
1020
+
1021
+ Avoid macros that generate class, property, or method definitions in
1022
+ headers to be used as public API. These only make the code hard to
1023
+ understand, and the language already has better ways of doing this.
1024
+
1025
+ Avoid macros that generate method implementations, or that generate declarations
1026
+ of variables that are later used outside of the macro. Macros shouldn't make
1027
+ code hard to understand by hiding where and how a variable is declared.
1028
+
1029
+ ```objectivec
1030
+ // AVOID:
1031
+
1032
+ #define ARRAY_ADDER(CLASS) \
1033
+ -(void)add ## CLASS ## :(CLASS *)obj toArray:(NSMutableArray *)array
1034
+
1035
+ ARRAY_ADDER(NSString) {
1036
+ if (array.count > 5) { // AVOID -- where is 'array' defined?
1037
+ ...
1038
+ }
1039
+ }
1040
+ ```
1041
+
1042
+ Examples of acceptable macro use include assertion and debug logging macros
1043
+ that are conditionally compiled based on build settings—often, these are
1044
+ not compiled into release builds.
1045
+
1046
+ <a id="Nonstandard_Extensions"></a>
1047
+
1048
+ ### Nonstandard Extensions
1049
+
1050
+ Nonstandard extensions to C/Objective-C may not be used unless otherwise
1051
+ specified.
1052
+
1053
+ Compilers support various extensions that are not part of standard C. Examples
1054
+ include compound statement expressions (e.g. `foo = ({ int x; Bar(&x); x })`).
1055
+
1056
+ #### The `__typeof__` Keyword
1057
+
1058
+ The `__typeof__` keyword is allowed in cases where the type doesn't aid in
1059
+ clarity for the reader. The `__typeof__` keyword is encouraged over other
1060
+ similar keywords (e.g., the `typeof` keyword) as it is supported in all language
1061
+ variants.
1062
+
1063
+ ```objectivec
1064
+ // GOOD:
1065
+
1066
+ __weak __typeof__(self) weakSelf = self;
1067
+ ```
1068
+
1069
+ ```objectivec
1070
+ // AVOID:
1071
+
1072
+ __typeof__(data) copiedData = [data copy]; // AVOID.
1073
+ __weak typeof(self) weakSelf = self; // AVOID.
1074
+ ```
1075
+
1076
+ #### The `__auto_type` Keyword and Type Deduction
1077
+
1078
+ Type deduction using the `__auto_type` keyword is allowed only for local
1079
+ variables of block and function pointer types. Avoid type deduction if a typedef
1080
+ already exists for the block or pointer type.
1081
+
1082
+ ```objectivec
1083
+ // GOOD:
1084
+
1085
+ __auto_type block = ^(NSString *arg1, int arg2) { ... };
1086
+ __auto_type functionPointer = &MyFunction;
1087
+
1088
+ typedef void(^SignInCallback)(Identity *, NSError *);
1089
+ SignInCallback signInCallback = ^(Identity *identity, NSError *error) { ... };
1090
+ ```
1091
+
1092
+ ```objectivec
1093
+ // AVOID:
1094
+
1095
+ __auto_type button = [self createButtonForInfo:info];
1096
+ __auto_type viewController = [[MyCustomViewControllerClass alloc] initWith...];
1097
+
1098
+ typedef void(^SignInCallback)(Identity *, NSError *);
1099
+ __auto_type signInCallback = ^(Identity *identity, NSError *error) { ... };
1100
+ ```
1101
+
1102
+ #### Approved Nonstandard Extensions
1103
+
1104
+ * The `__attribute__` keyword is approved as it is used in Apple API
1105
+ declarations.
1106
+ * The binary form of the conditional operator, `A ?: B`, is approved.
1107
+
1108
+ <a id="Cocoa_and_Objective-C_Features"></a>
1109
+
1110
+ ## Cocoa and Objective-C Features
1111
+
1112
+ <a id="Identify_Designated_Initializer"></a>
1113
+
1114
+ ### Identify Designated Initializers
1115
+
1116
+ Clearly identify your designated initializer(s).
1117
+
1118
+ It is important for subclassing that a class clearly identify its designated
1119
+ initializers. This allows a subclass to override a subset of initializers to
1120
+ initialize subclass state or invoke a new designated initializer provided by the
1121
+ subclass. Clearly identified designated initializers also make tracing through
1122
+ and debugging initialization code easier.
1123
+
1124
+ Prefer identifying designated initializers by annotating them with designated
1125
+ initializer attributes, e.g., `NS_DESIGNATED_INITIALIZER`. Declare designated
1126
+ initializers in comments when designated initializer attributes are not
1127
+ available. Prefer a single designated initializer unless there is a compelling
1128
+ reason or requirement for multiple designated initializers.
1129
+
1130
+ Support initializers inherited from superclasses by
1131
+ [overriding superclass designated initializers](#Override_Designated_Initializer)
1132
+ to ensure that all inherited initializers are directed through subclass
1133
+ designated initializers. When there is a compelling reason or requirement that
1134
+ an inherited initializer should not be supported, the initializer may be
1135
+ annotated with availability attributes (e.g., `NS_UNAVAILABLE`) to discourage
1136
+ usage; however, note that availability attributes alone do not completely
1137
+ protect against invalid initialization.
1138
+
1139
+ <a id="Override_Designated_Initializer"></a>
1140
+
1141
+ ### Override Designated Initializers
1142
+
1143
+ When writing a subclass that requires a new designated initializer, make sure
1144
+ you override any designated initializers of the superclass.
1145
+
1146
+ When declaring designated initializers on a class, remember that any
1147
+ initializers that were considered designated initializers on the superclass
1148
+ become convenience initializers of the subclass unless declared otherwise.
1149
+ Failure to override superclass designated initializers can result in bugs due to
1150
+ invalid initialization using superclass initializers. To avoid invalid
1151
+ initialization, ensure convenience initializers call through to a designated
1152
+ initializer.
1153
+
1154
+ <a id="Overridden_NSObject_Method_Placement"></a>
1155
+
1156
+ ### Overridden NSObject Method Placement
1157
+
1158
+ Put overridden methods of NSObject at the top of an `@implementation`.
1159
+
1160
+ This commonly applies to (but is not limited to) the `init...`, `copyWithZone:`,
1161
+ and `dealloc` methods. The `init...` methods should be grouped together,
1162
+ including those `init...` methods that are not `NSObject` overrides, followed by
1163
+ other typical `NSObject` methods such as `description`, `isEqual:`, and `hash`.
1164
+
1165
+ Convenience class factory methods for creating instances may precede the
1166
+ `NSObject` methods.
1167
+
1168
+ <a id="Initialization"></a>
1169
+
1170
+ ### Initialization
1171
+
1172
+ Don't initialize instance variables to `0` or `nil` in the `init` method; doing
1173
+ so is redundant.
1174
+
1175
+ All instance variables for a newly allocated object are [initialized
1176
+ to](https://developer.apple.com/library/mac/documentation/General/Conceptual/CocoaEncyclopedia/ObjectAllocation/ObjectAllocation.html)
1177
+ `0` (except for isa), so don't clutter up the init method by re-initializing
1178
+ variables to `0` or `nil`.
1179
+
1180
+ <a id="Instance_Variables_In_Headers_Should_Be_@protected_or_@private"></a>
1181
+
1182
+ ### Instance Variables In Headers Should Be @protected or @private
1183
+
1184
+ Instance variables should typically be declared in implementation files or
1185
+ auto-synthesized by properties. When ivars are declared in a header file, they
1186
+ should be marked `@protected` or `@private`.
1187
+
1188
+ ```objectivec
1189
+ // GOOD:
1190
+
1191
+ @interface MyClass : NSObject {
1192
+ @protected
1193
+ id _myInstanceVariable;
1194
+ }
1195
+ @end
1196
+ ```
1197
+
1198
+ <a id="Avoid_+new"></a>
1199
+
1200
+ ### Do Not Use +new
1201
+
1202
+ Do not invoke the `NSObject` class method `new`, nor override it in a subclass.
1203
+ `+new` is rarely used and contrasts greatly with initializer usage. Instead, use
1204
+ `+alloc` and `-init` methods to instantiate retained objects.
1205
+
1206
+ <a id="Keep_the_Public_API_Simple"></a>
1207
+
1208
+ ### Keep the Public API Simple
1209
+
1210
+ Keep your class simple; avoid "kitchen-sink" APIs. If a method doesn't need to
1211
+ be public, keep it out of the public interface.
1212
+
1213
+ Unlike C++, Objective-C doesn't differentiate between public and private
1214
+ methods; any message may be sent to an object. As a result, avoid placing
1215
+ methods in the public API unless they are actually expected to be used by a
1216
+ consumer of the class. This helps reduce the likelihood they'll be called when
1217
+ you're not expecting it. This includes methods that are being overridden from
1218
+ the parent class.
1219
+
1220
+ Since internal methods are not really private, it's easy to accidentally
1221
+ override a superclass's "private" method, thus making a very difficult bug to
1222
+ squash. In general, private methods should have a fairly unique name that will
1223
+ prevent subclasses from unintentionally overriding them.
1224
+
1225
+ <a id="#import_and_#include"></a>
1226
+
1227
+ ### #import and #include
1228
+
1229
+ `#import` Objective-C and Objective-C++ headers, and `#include` C/C++ headers.
1230
+
1231
+ C/C++ headers include other C/C++ headers using `#include`. Using `#import`
1232
+ on C/C++ headers prevents future inclusions using `#include` and could result in
1233
+ unintended compilation behavior.
1234
+
1235
+ C/C++ headers should provide their own `#define` guard.
1236
+
1237
+ <a id="Order_of_Includes"></a>
1238
+
1239
+ ### Order of Includes
1240
+
1241
+ The standard order for header inclusion is the related header, operating system
1242
+ headers, language library headers, and finally groups of headers for other
1243
+ dependencies.
1244
+
1245
+ The related header precedes others to ensure it has no hidden dependencies.
1246
+ For implementation files the related header is the header file.
1247
+ For test files the related header is the header containing the tested interface.
1248
+
1249
+ Separate each non-empty group of includes with one blank line. Within each group
1250
+ the includes should be ordered alphabetically.
1251
+
1252
+ Import headers using their path relative to the project's source directory.
1253
+
1254
+ ```objectivec
1255
+ // GOOD:
1256
+
1257
+ #import "ProjectX/BazViewController.h"
1258
+
1259
+ #import <Foundation/Foundation.h>
1260
+
1261
+ #include <unistd.h>
1262
+ #include <vector>
1263
+
1264
+ #include "base/basictypes.h"
1265
+ #include "base/integral_types.h"
1266
+ #import "base/mac/FOOComplexNumberSupport"
1267
+ #include "util/math/mathutil.h"
1268
+
1269
+ #import "ProjectX/BazModel.h"
1270
+ #import "Shared/Util/Foo.h"
1271
+ ```
1272
+
1273
+ <a id="Use_Umbrella_Headers_for_System_Frameworks"></a>
1274
+
1275
+ ### Use Umbrella Headers for System Frameworks
1276
+
1277
+ Import umbrella headers for system frameworks and system libraries rather than
1278
+ include individual files.
1279
+
1280
+ While it may seem tempting to include individual system headers from a framework
1281
+ such as Cocoa or Foundation, in fact it's less work on the compiler if you
1282
+ include the top-level root framework. The root framework is generally
1283
+ pre-compiled and can be loaded much more quickly. In addition, remember to use
1284
+ `@import` or `#import` rather than `#include` for Objective-C frameworks.
1285
+
1286
+ ```objectivec
1287
+ // GOOD:
1288
+
1289
+ @import UIKit; // GOOD.
1290
+ #import <Foundation/Foundation.h> // GOOD.
1291
+ ```
1292
+
1293
+ ```objectivec
1294
+ // AVOID:
1295
+
1296
+ #import <Foundation/NSArray.h> // AVOID.
1297
+ #import <Foundation/NSString.h>
1298
+ ...
1299
+ ```
1300
+
1301
+ ### Avoid Messaging the Current Object Within Initializers and `-dealloc`
1302
+
1303
+ Code in initializers and `-dealloc` should avoid invoking instance methods when
1304
+ possible.
1305
+
1306
+ Superclass initialization completes before subclass initialization. Until all
1307
+ classes have had a chance to initialize their instance state any method
1308
+ invocation on self may lead to a subclass operating on uninitialized instance
1309
+ state.
1310
+
1311
+ A similar issue exists for `-dealloc`, where a method invocation may cause a
1312
+ class to operate on state that has been deallocated.
1313
+
1314
+ One case where this is less obvious is property accessors. These can be
1315
+ overridden just like any other selector. Whenever practical, directly assign to
1316
+ and release ivars in initializers and `-dealloc`, rather than rely on accessors.
1317
+
1318
+ ```objectivec
1319
+ // GOOD:
1320
+
1321
+ - (instancetype)init {
1322
+ self = [super init];
1323
+ if (self) {
1324
+ _bar = 23; // GOOD.
1325
+ }
1326
+ return self;
1327
+ }
1328
+ ```
1329
+
1330
+ Beware of factoring common initialization code into helper methods:
1331
+
1332
+ - Methods can be overridden in subclasses, either deliberately, or
1333
+ accidentally due to naming collisions.
1334
+ - When editing a helper method, it may not be obvious that the code is being
1335
+ run from an initializer.
1336
+
1337
+ ```objectivec
1338
+ // AVOID:
1339
+
1340
+ - (instancetype)init {
1341
+ self = [super init];
1342
+ if (self) {
1343
+ self.bar = 23; // AVOID.
1344
+ [self sharedMethod]; // AVOID. Fragile to subclassing or future extension.
1345
+ }
1346
+ return self;
1347
+ }
1348
+ ```
1349
+
1350
+ ```objectivec
1351
+ // GOOD:
1352
+
1353
+ - (void)dealloc {
1354
+ [_notifier removeObserver:self]; // GOOD.
1355
+ }
1356
+ ```
1357
+
1358
+ ```objectivec
1359
+ // AVOID:
1360
+
1361
+ - (void)dealloc {
1362
+ [self removeNotifications]; // AVOID.
1363
+ }
1364
+ ```
1365
+
1366
+ There are common cases where a class may need to use properties and methods
1367
+ provided by a superclass during initialization. This commonly occurs for classes
1368
+ derived from UIKit and AppKit base classes, among other base classes. Use your
1369
+ judgement and knowledge of common practice when deciding whether to make an
1370
+ exception to this rule.
1371
+
1372
+ ### Avoid redundant property access
1373
+
1374
+ Code should avoid redundant property access. Prefer to assign a property value
1375
+ to a local variable when the property value is not expected to change and needs
1376
+ to be used multiple times.
1377
+
1378
+ ```objc
1379
+ // GOOD:
1380
+
1381
+ UIView *view = self.view;
1382
+ UIScrollView *scrollView = self.scrollView;
1383
+ [scrollView.leadingAnchor constraintEqualToAnchor:view.leadingAnchor].active = YES;
1384
+ [scrollView.trailingAnchor constraintEqualToAnchor:view.trailingAnchor].active = YES;
1385
+ ```
1386
+
1387
+ ```objc
1388
+ // AVOID:
1389
+
1390
+ [self.scrollView.loadingAnchor constraintEqualToAnchor:self.view.loadingAnchor].active = YES;
1391
+ [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor].active = YES;
1392
+ ```
1393
+
1394
+ When repeatedly referencing chained property invocations, prefer to capture the
1395
+ repeated expression in a local variable:
1396
+
1397
+ ```objc
1398
+ // AVOID:
1399
+
1400
+ foo.bar.baz.field1 = 10;
1401
+ foo.bar.baz.field2 = @"Hello";
1402
+ foo.bar.baz.field3 = 2.71828183;
1403
+ ```
1404
+
1405
+ ```objc
1406
+ // GOOD:
1407
+
1408
+ Baz *baz = foo.bar.baz;
1409
+ baz.field1 = 10;
1410
+ baz.field2 = @"Hello";
1411
+ baz.field3 = 2.71828183;
1412
+ ```
1413
+
1414
+ Redundantly accessing the same properties results in multiple message dispatches
1415
+ to fetch the same value, and under ARC requires retains and releases of any
1416
+ returned objects; the compiler cannot optimize away these extra operations,
1417
+ leading to slower execution and substantial increases in binary size.
1418
+
1419
+
1420
+ <a id="Mutables_Copies_Ownership"></a>
1421
+
1422
+ ### Mutables, Copies and Ownership
1423
+
1424
+ For [Foundation and other hierarchies containing both immutable and mutable
1425
+ subclasses](https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/ObjectMutability/ObjectMutability.html)
1426
+ a mutable subclass may be substituted for an immutable so long as the
1427
+ immutable's contract is honored.
1428
+
1429
+ The most common example of this sort of substitution are ownership transfers,
1430
+ particularly for return values. In these cases an additional copy is not
1431
+ necessary and returning the mutable subclass is more efficient.
1432
+ [Callers are expected to treat return values as their declared type](https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/ObjectMutability/ObjectMutability.html#//apple_ref/doc/uid/TP40010810-CH5-SW67),
1433
+ and thus the return value will be treated as an immutable going forward.
1434
+
1435
+ ```objectivec
1436
+ // GOOD:
1437
+
1438
+ - (NSArray *)listOfThings {
1439
+ NSMutableArray *generatedList = [NSMutableArray array];
1440
+ for (NSInteger i = 0; i < _someLimit; i++) {
1441
+ [generatedList addObject:[self thingForIndex:i]];
1442
+ }
1443
+ // Copy not necessary, ownership of generatedList is transferred.
1444
+ return generatedList;
1445
+ }
1446
+ ```
1447
+
1448
+ This rule also applies to classes where only a mutable variant exists so long as
1449
+ the ownership transfer is clear. Protos are a common example.
1450
+
1451
+ ```objectivec
1452
+ // GOOD:
1453
+
1454
+ - (SomeProtoMessage *)someMessageForValue:(BOOL)value {
1455
+ SomeProtoMessage *message = [SomeProtoMessage message];
1456
+ message.someValue = value;
1457
+ return message;
1458
+ }
1459
+ ```
1460
+
1461
+ It is not necessary to create a local immutable copy of a mutable type to match
1462
+ the method signature of a method being called so long as the mutable argument
1463
+ will not change for the duration of the method call. Called methods are expected
1464
+ to treat arguments as the declared type, and take
1465
+ [defensive copies](#Defensive_Copies)
1466
+ ([referred to by Apple as "snapshots"](https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/ObjectMutability/ObjectMutability.html#//apple_ref/doc/uid/TP40010810-CH5-SW68))
1467
+ if they intend to retain those arguments beyond the duration of the call.
1468
+
1469
+ ```objectivec
1470
+ // AVOID:
1471
+
1472
+ NSMutableArray *updatedThings = [NSMutableArray array];
1473
+ [updatedThings addObject:newThing];
1474
+ [_otherManager updateWithCurrentThings:[updatedThings copy]]; // AVOID
1475
+ ```
1476
+
1477
+ <a id="Defensive_Copies"></a>
1478
+ <a id="Setters_copy_NSStrings"></a>
1479
+
1480
+ ### Copy Potentially Mutable Objects
1481
+
1482
+ Code receiving and retaining collections or other types with
1483
+ [mutable variants](https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/ObjectMutability/ObjectMutability.html)
1484
+ should consider that the passed object may be mutable, and thus an immutable or
1485
+ mutable copy should be retained instead of the original object. In particular,
1486
+ initializers and setters
1487
+ [should copy instead of retaining objects whose types have mutable variants](https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/ObjectMutability/ObjectMutability.html#//apple_ref/doc/uid/TP40010810-CH5-SW68).
1488
+
1489
+ Synthesized accessors should use the `copy` keyword to ensure the generated code
1490
+ matches these expectations.
1491
+
1492
+ NOTE: [The `copy` property keyword only affects the synthesized setter and has
1493
+ no effect on
1494
+ getters](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW27).
1495
+ Since property keywords have no effect on direct ivar access custom accessors
1496
+ must implement the same copy semantics.
1497
+
1498
+ ```objectivec
1499
+ // GOOD:
1500
+
1501
+ @property(nonatomic, copy) NSString *name;
1502
+ @property(nonatomic, copy) NSSet<FilterThing *> *filters;
1503
+
1504
+ - (instancetype)initWithName:(NSString *)name
1505
+ filters:(NSSet<FilterThing *> *)filters {
1506
+ self = [super init];
1507
+ if (self) {
1508
+ _name = [name copy];
1509
+ _filters = [filters copy];
1510
+ }
1511
+ return self;
1512
+ }
1513
+
1514
+ - (void)setFilters:(NSSet<FilterThing *> *)filters {
1515
+ // Ensure that we retain an immutable collection.
1516
+ _filters = [filters copy];
1517
+ }
1518
+ ```
1519
+
1520
+ Similarly, getters must return types that match the contract expectations of the
1521
+ immutable types they return.
1522
+
1523
+ ```objectivec
1524
+ // GOOD:
1525
+
1526
+
1527
+ @implementation Foo {
1528
+ NSMutableArray<ContentThing *> *_currentContent;
1529
+ }
1530
+
1531
+ - (NSArray<ContentThing *> *)currentContent {
1532
+ return [_currentContent copy];
1533
+ }
1534
+
1535
+ ```
1536
+
1537
+ All Objective-C protos are mutable and typically should be copied rather than
1538
+ retained
1539
+ [except in clear cases of ownership transfer](#Mutables_Copies_Ownership).
1540
+
1541
+ ```objectivec
1542
+ // GOOD:
1543
+
1544
+ - (void)setFooMessage:(FooMessage *)fooMessage {
1545
+ // Copy proto to ensure no other retainer can mutate our value.
1546
+ _fooMessage = [fooMessage copy];
1547
+ }
1548
+
1549
+ - (FooMessage *)fooMessage {
1550
+ // Copy proto to return so that caller cannot mutate our value.
1551
+ return [_fooMessage copy];
1552
+ }
1553
+ ```
1554
+
1555
+ Asynchronous code should copy potentially mutable objects prior to dispatch.
1556
+ Objects captured by blocks are retained but not copied.
1557
+
1558
+ ```objectivec
1559
+ // GOOD:
1560
+
1561
+ - (void)doSomethingWithThings:(NSArray<Thing *> *)things {
1562
+ NSArray<Thing *> *thingsToWorkOn = [things copy];
1563
+ dispatch_async(_workQueue, ^{
1564
+ for (id<Thing> thing in thingsToWorkOn) {
1565
+ ...
1566
+ }
1567
+ });
1568
+ }
1569
+ ```
1570
+
1571
+ NOTE: It is unnecessary to copy objects that do not have mutable variants, e.g.
1572
+ `NSURL`, `NSNumber`, `NSDate`, `UIColor`, etc.
1573
+
1574
+ <a id="Use_Lightweight_Generics_to_Document_Contained_Types"></a>
1575
+
1576
+ ### Use Lightweight Generics to Document Contained Types
1577
+
1578
+ All projects compiling on Xcode 7 or newer versions should make use of the
1579
+ Objective-C lightweight generics notation to type contained objects.
1580
+
1581
+ Every `NSArray`, `NSDictionary`, or `NSSet` reference should be declared using
1582
+ lightweight generics for improved type safety and to explicitly document usage.
1583
+
1584
+ ```objectivec
1585
+ // GOOD:
1586
+
1587
+ @property(nonatomic, copy) NSArray<Location *> *locations;
1588
+ @property(nonatomic, copy, readonly) NSSet<NSString *> *identifiers;
1589
+
1590
+ NSMutableArray<MyLocation *> *mutableLocations = [otherObject.locations mutableCopy];
1591
+ ```
1592
+
1593
+ If the fully-annotated types become complex, consider using a typedef to
1594
+ preserve readability.
1595
+
1596
+ ```objectivec
1597
+ // GOOD:
1598
+
1599
+ typedef NSSet<NSDictionary<NSString *, NSDate *> *> TimeZoneMappingSet;
1600
+ TimeZoneMappingSet *timeZoneMappings = [TimeZoneMappingSet setWithObjects:...];
1601
+ ```
1602
+
1603
+ Use the most descriptive common superclass or protocol available. In the most
1604
+ generic case when nothing else is known, declare the collection to be explicitly
1605
+ heterogeneous using id.
1606
+
1607
+ ```objectivec
1608
+ // GOOD:
1609
+
1610
+ @property(nonatomic, copy) NSArray<id> *unknowns;
1611
+ ```
1612
+
1613
+ <a id="Avoid_Throwing_Exceptions"></a>
1614
+
1615
+ ### Avoid Throwing Exceptions
1616
+
1617
+ Don't `@throw` Objective-C exceptions, but you should be prepared to catch them
1618
+ from third-party or OS calls.
1619
+
1620
+ This follows the recommendation to use error objects for error delivery in
1621
+ [Apple's Introduction to Exception Programming Topics for
1622
+ Cocoa](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Exceptions/Exceptions.html).
1623
+
1624
+ We do compile with `-fobjc-exceptions` (mainly so we get `@synchronized`), but
1625
+ we don't `@throw`. Use of `@try`, `@catch`, and `@finally` are allowed when
1626
+ required to properly use 3rd party code or libraries. If you do use them, please
1627
+ document exactly which methods you expect to throw.
1628
+
1629
+ <a id="nil_Checks"></a>
1630
+
1631
+ ### `nil` Checks
1632
+
1633
+ Avoid `nil` pointer checks that exist only to prevent sending messages to `nil`.
1634
+ Sending a message to `nil` [reliably
1635
+ returns](http://www.sealiesoftware.com/blog/archive/2012/2/29/objc_explain_return_value_of_message_to_nil.html)
1636
+ `nil` as a pointer, zero as an integer or floating-point value, structs
1637
+ initialized to `0`, and `_Complex` values equal to `{0, 0}`.
1638
+
1639
+ ```objectivec
1640
+ // AVOID:
1641
+
1642
+ if (dataSource) { // AVOID.
1643
+ [dataSource moveItemAtIndex:1 toIndex:0];
1644
+ }
1645
+ ```
1646
+
1647
+ ```objectivec
1648
+ // GOOD:
1649
+
1650
+ [dataSource moveItemAtIndex:1 toIndex:0]; // GOOD.
1651
+ ```
1652
+
1653
+ Note that this applies to `nil` as a message target, not as a parameter value.
1654
+ Individual methods may or may not safely handle `nil` parameter values.
1655
+
1656
+ Note too that this is distinct from checking C/C++ pointers and block pointers
1657
+ against `NULL`, which the runtime does not handle and will cause your
1658
+ application to crash. You still need to make sure you do not dereference a
1659
+ `NULL` pointer.
1660
+
1661
+ ### Nullability
1662
+
1663
+ Interfaces can be decorated with nullability annotations to describe how the
1664
+ interface should be used and how it behaves. Use of nullability regions (e.g.,
1665
+ `NS_ASSUME_NONNULL_BEGIN` and `NS_ASSUME_NONNULL_END`) and explicit nullability
1666
+ annotations are both accepted. Prefer using the `_Nullable` and `_Nonnull`
1667
+ keywords over the `__nullable` and `__nonnull` keywords. For Objective-C methods
1668
+ and properties prefer using the context-sensitive, non-underscored keywords,
1669
+ e.g., `nonnull` and `nullable`.
1670
+
1671
+ ```objectivec
1672
+ // GOOD:
1673
+
1674
+ /** A class representing an owned book. */
1675
+ @interface GTMBook : NSObject
1676
+
1677
+ /** The title of the book. */
1678
+ @property(nonatomic, readonly, copy, nonnull) NSString *title;
1679
+
1680
+ /** The author of the book, if one exists. */
1681
+ @property(nonatomic, readonly, copy, nullable) NSString *author;
1682
+
1683
+ /** The owner of the book. Setting nil resets to the default owner. */
1684
+ @property(nonatomic, copy, null_resettable) NSString *owner;
1685
+
1686
+ /** Initializes a book with a title and an optional author. */
1687
+ - (nonnull instancetype)initWithTitle:(nonnull NSString *)title
1688
+ author:(nullable NSString *)author
1689
+ NS_DESIGNATED_INITIALIZER;
1690
+
1691
+ /** Returns nil because a book is expected to have a title. */
1692
+ - (nullable instancetype)init;
1693
+
1694
+ @end
1695
+
1696
+ /** Loads books from the file specified by the given path. */
1697
+ NSArray<GTMBook *> *_Nullable GTMLoadBooksFromFile(NSString *_Nonnull path);
1698
+ ```
1699
+
1700
+ ```objectivec
1701
+ // AVOID:
1702
+
1703
+ NSArray<GTMBook *> *__nullable GTMLoadBooksFromTitle(NSString *__nonnull path);
1704
+ ```
1705
+
1706
+ Do not assume that a pointer is not null based on a nonnull qualifier, because
1707
+ the compiler only checks a subset of such cases, and does not guarantee that the
1708
+ pointer is not null. Avoid intentionally violating nullability semantics
1709
+ of function, method, and property declarations.
1710
+
1711
+ <a id="BOOL_Pitfalls"></a>
1712
+
1713
+ ### BOOL Pitfalls
1714
+
1715
+ <a id="BOOL_Expressions_Conversions"></a>
1716
+ #### BOOL Expressions and Conversions
1717
+
1718
+ Be careful when converting general integral values to `BOOL`. Avoid comparing
1719
+ directly with `YES` or comparing multiple `BOOL` values with comparison
1720
+ operators.
1721
+
1722
+ `BOOL` on some Apple platforms (notably Intel macOS, watchOS, and 32-bit iOS)
1723
+ is defined as a signed `char`, so it may have values other than `YES` (`1`) and
1724
+ `NO` (`0`). Do not cast or convert general integral values directly to `BOOL`.
1725
+
1726
+ Common mistakes include casting or converting an array's size, a pointer value,
1727
+ or the result of a bitwise logic operation to a `BOOL`. These operations can
1728
+ depend on the value of the last byte of the integer value and result in an
1729
+ unexpected `NO` value. Operations with NS_OPTIONS values and flag masking are
1730
+ especially common errors.
1731
+
1732
+ When converting a general integral value to a `BOOL`, use conditional operators
1733
+ to return a `YES` or `NO` value.
1734
+
1735
+ You can safely interchange and convert `BOOL`, `_Bool` and `bool` (see C++ Std
1736
+ 4.7.4, 4.12 and C99 Std 6.3.1.2). Use `BOOL` in Objective-C method signatures.
1737
+
1738
+ Using logical operators (`&&`, `||` and `!`) with `BOOL` is also valid and will
1739
+ return values that can be safely converted to `BOOL` without the need for a
1740
+ conditional operator.
1741
+
1742
+ ```objectivec
1743
+ // AVOID:
1744
+
1745
+ - (BOOL)isBold {
1746
+ return [self fontTraits] & NSFontBoldTrait; // AVOID.
1747
+ }
1748
+ - (BOOL)isValid {
1749
+ return [self stringValue]; // AVOID.
1750
+ }
1751
+ - (BOOL)isLongEnough {
1752
+ return (BOOL)([self stringValue].count); // AVOID.
1753
+ }
1754
+ ```
1755
+
1756
+ ```objectivec
1757
+ // GOOD:
1758
+
1759
+ - (BOOL)isBold {
1760
+ return ([self fontTraits] & NSFontBoldTrait) ? YES : NO;
1761
+ }
1762
+ - (BOOL)isValid {
1763
+ return [self stringValue] != nil;
1764
+ }
1765
+ - (BOOL)isLongEnough {
1766
+ return [self stringValue].count > 0;
1767
+ }
1768
+ - (BOOL)isEnabled {
1769
+ return [self isValid] && [self isBold];
1770
+ }
1771
+ ```
1772
+
1773
+ Don't directly compare `BOOL` variables directly with `YES`. Not only is
1774
+ it harder to read for those well-versed in C, but the first point above
1775
+ demonstrates that return values may not always be what you expect.
1776
+
1777
+ ```objectivec
1778
+ // AVOID:
1779
+
1780
+ BOOL great = [foo isGreat];
1781
+ if (great == YES) { // AVOID.
1782
+ // ...be great!
1783
+ }
1784
+ ```
1785
+
1786
+ ```objectivec
1787
+ // GOOD:
1788
+
1789
+ BOOL great = [foo isGreat];
1790
+ if (great) { // GOOD.
1791
+ // ...be great!
1792
+ }
1793
+ ```
1794
+
1795
+ Don't directly compare `BOOL` values using comparison operators. `BOOL`
1796
+ values that are true may not be equal. Use logical operators in place
1797
+ of bitwise comparisons of `BOOL` values.
1798
+
1799
+ ```objectivec
1800
+ // AVOID:
1801
+
1802
+ if (oldBOOLValue != newBOOLValue) { // AVOID.
1803
+ // ... code that should only run when the value changes.
1804
+ }
1805
+ ```
1806
+
1807
+ ```objectivec
1808
+ // GOOD:
1809
+
1810
+ if ((!oldBoolValue && newBoolValue) || (oldBoolValue && !newBoolValue)) { // GOOD.
1811
+ // ... code that should only run when the value changes.
1812
+ }
1813
+
1814
+ // GOOD, the results of logical operators on BOOLs are safe to compare.
1815
+ if (!oldBoolValue != !newBoolValue) {
1816
+ // ... code that should only run when the value changes.
1817
+ }
1818
+ ```
1819
+
1820
+ #### BOOL Literals
1821
+
1822
+ The [BOOL NSNumber literals](https://clang.llvm.org/docs/ObjectiveCLiterals.html#nsnumber-literals)
1823
+ are `@YES` and `@NO` which are equivalent to `[NSNumber numberWithBool:...]`.
1824
+
1825
+ Avoid using [boxed expressions](https://clang.llvm.org/docs/ObjectiveCLiterals.html#boxed-expressions)
1826
+ to create BOOL values, including simple expressions like `@(YES)`.
1827
+ Boxed expressions suffer from [the same pitfalls as other BOOL expressions]
1828
+ (#BOOL_Expressions_Conversions) as boxing general integral values can
1829
+ produce true or false `NSNumbers` that are not equal to `@YES` and `@NO`.
1830
+
1831
+ When converting a general integral value to a BOOL literal, use conditional
1832
+ operators to convert to `@YES` or `@NO`. Do not embed a conditional operator
1833
+ inside a boxed expression as this is equivalent to boxing general integral
1834
+ values even when the result of the operation is a BOOL.
1835
+
1836
+ ```objectivec
1837
+ // AVOID:
1838
+
1839
+ [_boolArray addValue:@(YES)]; // AVOID boxing even in simple cases.
1840
+ NSNumber *isBold = @(self.fontTraits & NSFontBoldTrait); // AVOID.
1841
+ NSNumber *hasContent = @([self stringValue].length); // AVOID.
1842
+ NSNumber *isValid = @([self stringValue]); // AVOID.
1843
+ NSNumber *isStringNotNil = @([self stringValue] ? YES : NO); // AVOID.
1844
+ ```
1845
+
1846
+ ```objectivec
1847
+ // GOOD:
1848
+
1849
+ [_boolArray addValue:@YES]; // GOOD.
1850
+ NSNumber *isBold = self.fontTraits & NSFontBoldTrait ? @YES : @NO; // GOOD.
1851
+ NSNumber *hasContent = [self stringValue].length ? @YES : @NO; // GOOD.
1852
+ NSNumber *isValid = [self stringValue] ? @YES : @NO; // GOOD.
1853
+ NSNumber *isStringNotNil = [self stringValue] ? @YES : @NO; // GOOD.
1854
+ ```
1855
+
1856
+ <a id="Interfaces_Without_Instance_Variables"></a>
1857
+ <a id="interfaces-without-instance-variables"></a>
1858
+
1859
+ ### Containers Without Instance Variables
1860
+
1861
+ Omit the empty set of braces on interfaces, class extensions, and
1862
+ implementations without any instance variable declarations.
1863
+
1864
+ ```objectivec
1865
+ // GOOD:
1866
+
1867
+ @interface MyClass : NSObject
1868
+ // Does a lot of stuff.
1869
+ - (void)fooBarBam;
1870
+ @end
1871
+
1872
+ @interface MyClass ()
1873
+ - (void)classExtensionMethod;
1874
+ @end
1875
+
1876
+ @implementation MyClass
1877
+ // Actual implementation.
1878
+ @end
1879
+ ```
1880
+
1881
+ ```objectivec
1882
+ // AVOID:
1883
+
1884
+ @interface MyClass : NSObject {
1885
+ }
1886
+ // Does a lot of stuff.
1887
+ - (void)fooBarBam;
1888
+ @end
1889
+
1890
+ @interface MyClass () {
1891
+ }
1892
+ - (void)classExtensionMethod;
1893
+ @end
1894
+
1895
+ @implementation MyClass {
1896
+ }
1897
+ // Actual implementation.
1898
+ @end
1899
+ ```
1900
+
1901
+ <a id="Cocoa_Patterns"></a>
1902
+
1903
+ ## Cocoa Patterns
1904
+
1905
+ <a id="Delegate_Pattern"></a>
1906
+
1907
+ ### Delegate Pattern
1908
+
1909
+ Delegates, target objects, and block pointers should not be retained when doing
1910
+ so would create a retain cycle.
1911
+
1912
+ To avoid causing a retain cycle, a delegate or target pointer should be released
1913
+ as soon as it is clear there will no longer be a need to message the object.
1914
+
1915
+ If there is no clear time at which the delegate or target pointer is no longer
1916
+ needed, the pointer should only be retained weakly.
1917
+
1918
+ Block pointers cannot be retained weakly. To avoid causing retain cycles in the
1919
+ client code, block pointers should be used for callbacks only where they can be
1920
+ explicitly released after they have been called or once they are no longer
1921
+ needed. Otherwise, callbacks should be done via weak delegate or target
1922
+ pointers.
1923
+
1924
+ <a id="Objective-C++"></a>
1925
+
1926
+ ## Objective-C++
1927
+
1928
+ <a id="Style_Matches_the_Language"></a>
1929
+
1930
+ ### Style Matches the Language
1931
+
1932
+ Within an Objective-C++ source file, follow the style for the language of the
1933
+ function or method you're implementing. In order to minimize clashes between the
1934
+ differing naming styles when mixing Cocoa/Objective-C and C++, follow the style
1935
+ of the method being implemented.
1936
+
1937
+ For code in an `@implementation` block, use the Objective-C naming rules. For
1938
+ code in a method of a C++ class, use the C++ naming rules.
1939
+
1940
+ For code in an Objective-C++ file outside of a class implementation, be
1941
+ consistent within the file.
1942
+
1943
+ ```objectivec++
1944
+ // GOOD:
1945
+
1946
+ // file: cross_platform_header.h
1947
+
1948
+ class CrossPlatformAPI {
1949
+ public:
1950
+ ...
1951
+ int DoSomethingPlatformSpecific(); // impl on each platform
1952
+ private:
1953
+ int an_instance_var_;
1954
+ };
1955
+
1956
+ // file: mac_implementation.mm
1957
+ #include "cross_platform_header.h"
1958
+
1959
+ /** A typical Objective-C class, using Objective-C naming. */
1960
+ @interface MyDelegate : NSObject {
1961
+ @private
1962
+ int _instanceVar;
1963
+ CrossPlatformAPI* _backEndObject;
1964
+ }
1965
+
1966
+ - (void)respondToSomething:(id)something;
1967
+
1968
+ @end
1969
+
1970
+ @implementation MyDelegate
1971
+
1972
+ - (void)respondToSomething:(id)something {
1973
+ // bridge from Cocoa through our C++ backend
1974
+ _instanceVar = _backEndObject->DoSomethingPlatformSpecific();
1975
+ NSString* tempString = [NSString stringWithFormat:@"%d", _instanceVar];
1976
+ NSLog(@"%@", tempString);
1977
+ }
1978
+
1979
+ @end
1980
+
1981
+ /** The platform-specific implementation of the C++ class, using C++ naming. */
1982
+ int CrossPlatformAPI::DoSomethingPlatformSpecific() {
1983
+ NSString* temp_string = [NSString stringWithFormat:@"%d", an_instance_var_];
1984
+ NSLog(@"%@", temp_string);
1985
+ return [temp_string intValue];
1986
+ }
1987
+ ```
1988
+
1989
+ Projects may opt to use an 80 column line length limit for consistency with
1990
+ Google's C++ style guide.
1991
+
1992
+ <a id="Spacing_and_Formatting"></a>
1993
+
1994
+ ## Spacing and Formatting
1995
+
1996
+ <a id="Spaces_vs._Tabs"></a>
1997
+
1998
+ ### Spaces vs. Tabs
1999
+
2000
+ Use only spaces, and indent 2 spaces at a time. We use spaces for indentation.
2001
+ Do not use tabs in your code.
2002
+
2003
+ You should set your editor to emit spaces when you hit the tab key, and to trim
2004
+ trailing spaces on lines.
2005
+
2006
+ <a id="Line_Length"></a>
2007
+
2008
+ ### Line Length
2009
+
2010
+ The maximum line length for Objective-C files is 100 columns.
2011
+
2012
+ <a id="Method_Declarations_and_Definitions"></a>
2013
+
2014
+ ### Method Declarations and Definitions
2015
+
2016
+ One space should be used between the `-` or `+` and the return type. In general,
2017
+ there should be no spacing in the parameter list except between parameters.
2018
+
2019
+ Methods should look like this:
2020
+
2021
+ ```objectivec
2022
+ // GOOD:
2023
+
2024
+ - (void)doSomethingWithString:(NSString *)theString {
2025
+ ...
2026
+ }
2027
+ ```
2028
+
2029
+ The spacing before the asterisk is optional. When adding new code, be consistent
2030
+ with the surrounding file's style.
2031
+
2032
+ If a method declaration does not fit on a single line, put each parameter on its
2033
+ own line. All lines except the first should be indented at least four spaces.
2034
+ Colons before parameters should be aligned on all lines. If the colon before the
2035
+ parameter on the first line of a method declaration is positioned such that
2036
+ colon alignment would cause indentation on a subsequent line to be less than
2037
+ four spaces, then colon alignment is only required for all lines except the
2038
+ first. If a parameter declared after the `:` in a method declaration or
2039
+ definition would cause the line limit to be exceeded, wrap the content to the
2040
+ next line indented by at least four spaces.
2041
+
2042
+ ```objectivec
2043
+ // GOOD:
2044
+
2045
+ - (void)doSomethingWithFoo:(GTMFoo *)theFoo
2046
+ rect:(NSRect)theRect
2047
+ interval:(float)theInterval {
2048
+ ...
2049
+ }
2050
+
2051
+ - (void)shortKeyword:(GTMFoo *)theFoo
2052
+ longerKeyword:(NSRect)theRect
2053
+ someEvenLongerKeyword:(float)theInterval
2054
+ error:(NSError **)theError {
2055
+ ...
2056
+ }
2057
+
2058
+ - (id<UIAdaptivePresentationControllerDelegate>)
2059
+ adaptivePresentationControllerDelegateForViewController:(UIViewController *)viewController;
2060
+
2061
+ - (void)presentWithAdaptivePresentationControllerDelegate:
2062
+ (id<UIAdaptivePresentationControllerDelegate>)delegate;
2063
+
2064
+ - (void)updateContentHeaderViewForExpansionToContentOffset:(CGPoint)contentOffset
2065
+ withController:
2066
+ (GTMCollectionExpansionController *)controller;
2067
+
2068
+ ```
2069
+
2070
+ ### Function Declarations and Definitions
2071
+
2072
+ Prefer putting the return type on the same line as the function name and append
2073
+ all parameters on the same line if they will fit. Wrap parameter lists which do
2074
+ not fit on a single line as you would wrap arguments in a [function
2075
+ call](#Function_Calls).
2076
+
2077
+ ```objectivec
2078
+ // GOOD:
2079
+
2080
+ NSString *GTMVersionString(int majorVersion, int minorVersion) {
2081
+ ...
2082
+ }
2083
+
2084
+ void GTMSerializeDictionaryToFileOnDispatchQueue(
2085
+ NSDictionary<NSString *, NSString *> *dictionary,
2086
+ NSString *filename,
2087
+ dispatch_queue_t queue) {
2088
+ ...
2089
+ }
2090
+ ```
2091
+
2092
+ Function declarations and definitions should also satisfy the following
2093
+ conditions:
2094
+
2095
+ * The opening parenthesis must always be on the same line as the function
2096
+ name.
2097
+ * If you cannot fit the return type and the function name on a single line,
2098
+ break between them and do not indent the function name.
2099
+ * There should never be a space before the opening parenthesis.
2100
+ * There should never be a space between function parentheses and parameters.
2101
+ * The open curly brace is always on the end of the last line of the function
2102
+ declaration, not the start of the next line.
2103
+ * The close curly brace is either on the last line by itself or on the same
2104
+ line as the open curly brace.
2105
+ * There should be a space between the close parenthesis and the open curly
2106
+ brace.
2107
+ * All parameters should be aligned if possible.
2108
+ * Function scopes should be indented 2 spaces.
2109
+ * Wrapped parameters should have a 4 space indent.
2110
+
2111
+ <a id="Conditionals"></a>
2112
+
2113
+ ### Conditionals
2114
+
2115
+ Include a space after `if`, `while`, `for`, and `switch`, and around comparison
2116
+ operators.
2117
+
2118
+ ```objectivec
2119
+ // GOOD:
2120
+
2121
+ for (int i = 0; i < 5; ++i) {
2122
+ }
2123
+
2124
+ while (test) {};
2125
+ ```
2126
+
2127
+ Braces may be omitted when a loop body or conditional statement fits on a single
2128
+ line.
2129
+
2130
+ ```objectivec
2131
+ // GOOD:
2132
+
2133
+ if (hasSillyName) LaughOutLoud();
2134
+
2135
+ for (int i = 0; i < 10; i++) {
2136
+ BlowTheHorn();
2137
+ }
2138
+ ```
2139
+
2140
+ ```objectivec
2141
+ // AVOID:
2142
+
2143
+ if (hasSillyName)
2144
+ LaughOutLoud(); // AVOID.
2145
+
2146
+ for (int i = 0; i < 10; i++)
2147
+ BlowTheHorn(); // AVOID.
2148
+ ```
2149
+
2150
+ If an `if` clause has an `else` clause, both clauses should use braces.
2151
+
2152
+ ```objectivec
2153
+ // GOOD:
2154
+
2155
+ if (hasBaz) {
2156
+ foo();
2157
+ } else { // The else goes on the same line as the closing brace.
2158
+ bar();
2159
+ }
2160
+ ```
2161
+
2162
+ ```objectivec
2163
+ // AVOID:
2164
+
2165
+ if (hasBaz) foo();
2166
+ else bar(); // AVOID.
2167
+
2168
+ if (hasBaz) {
2169
+ foo();
2170
+ } else bar(); // AVOID.
2171
+ ```
2172
+
2173
+ Intentional fall-through to the next case should be documented with a comment
2174
+ unless the case has no intervening code before the next case.
2175
+
2176
+ ```objectivec
2177
+ // GOOD:
2178
+
2179
+ switch (i) {
2180
+ case 1:
2181
+ ...
2182
+ break;
2183
+ case 2:
2184
+ j++;
2185
+ // Falls through.
2186
+ case 3: {
2187
+ int k;
2188
+ ...
2189
+ break;
2190
+ }
2191
+ case 4:
2192
+ case 5:
2193
+ case 6: break;
2194
+ }
2195
+ ```
2196
+
2197
+ <a id="Expressions"></a>
2198
+
2199
+ ### Expressions
2200
+
2201
+ Use a space around binary operators and assignments. Omit a space for a unary
2202
+ operator. Do not add spaces inside parentheses.
2203
+
2204
+ ```objectivec
2205
+ // GOOD:
2206
+
2207
+ x = 0;
2208
+ v = w * x + y / z;
2209
+ v = -y * (x + z);
2210
+ ```
2211
+
2212
+ Factors in an expression may omit spaces.
2213
+
2214
+ ```objectivec
2215
+ // GOOD:
2216
+
2217
+ v = w*x + y/z;
2218
+ ```
2219
+
2220
+ <a id="Method_Invocations"></a>
2221
+
2222
+ ### Method Invocations
2223
+
2224
+ Method invocations should be formatted much like method declarations.
2225
+
2226
+ When there's a choice of formatting styles, follow the convention already used
2227
+ in a given source file. Invocations should have all arguments on one line:
2228
+
2229
+ ```objectivec
2230
+ // GOOD:
2231
+
2232
+ [myObject doFooWith:arg1 name:arg2 error:arg3];
2233
+ ```
2234
+
2235
+ or have one argument per line, with colons aligned:
2236
+
2237
+ ```objectivec
2238
+ // GOOD:
2239
+
2240
+ [myObject doFooWith:arg1
2241
+ name:arg2
2242
+ error:arg3];
2243
+ ```
2244
+
2245
+ Don't use any of these styles:
2246
+
2247
+ ```objectivec
2248
+ // AVOID:
2249
+
2250
+ [myObject doFooWith:arg1 name:arg2 // some lines with >1 arg
2251
+ error:arg3];
2252
+
2253
+ [myObject doFooWith:arg1
2254
+ name:arg2 error:arg3];
2255
+
2256
+ [myObject doFooWith:arg1
2257
+ name:arg2 // aligning keywords instead of colons
2258
+ error:arg3];
2259
+ ```
2260
+
2261
+ As with declarations and definitions, when the first keyword is shorter than the
2262
+ others, indent the later lines by at least four spaces, maintaining colon
2263
+ alignment:
2264
+
2265
+ ```objectivec
2266
+ // GOOD:
2267
+
2268
+ [myObj short:arg1
2269
+ longKeyword:arg2
2270
+ evenLongerKeyword:arg3
2271
+ error:arg4];
2272
+ ```
2273
+
2274
+ Invocations containing multiple inlined blocks may have their parameter names
2275
+ left-aligned at a four space indent.
2276
+
2277
+ <a id="Function_Calls"></a>
2278
+
2279
+ ### Function Calls
2280
+
2281
+ Function calls should include as many parameters as fit on each line, except
2282
+ where shorter lines are needed for clarity or documentation of the parameters.
2283
+
2284
+ Continuation lines for function parameters may be indented to align with the
2285
+ opening parenthesis, or may have a four-space indent.
2286
+
2287
+ ```objectivec
2288
+ // GOOD:
2289
+
2290
+ CFArrayRef array = CFArrayCreate(kCFAllocatorDefault, objects, numberOfObjects,
2291
+ &kCFTypeArrayCallBacks);
2292
+
2293
+ NSString *string = NSLocalizedStringWithDefaultValue(@"FEET", @"DistanceTable",
2294
+ resourceBundle, @"%@ feet", @"Distance for multiple feet");
2295
+
2296
+ UpdateTally(scores[x] * y + bases[x], // Score heuristic.
2297
+ x, y, z);
2298
+
2299
+ TransformImage(image,
2300
+ x1, x2, x3,
2301
+ y1, y2, y3,
2302
+ z1, z2, z3);
2303
+ ```
2304
+
2305
+ Use local variables with descriptive names to shorten function calls and reduce
2306
+ nesting of calls.
2307
+
2308
+ ```objectivec
2309
+ // GOOD:
2310
+
2311
+ double scoreHeuristic = scores[x] * y + bases[x];
2312
+ UpdateTally(scoreHeuristic, x, y, z);
2313
+ ```
2314
+
2315
+ <a id="Exceptions"></a>
2316
+
2317
+ ### Exceptions
2318
+
2319
+ Format exceptions with `@catch` and `@finally` labels on the same line as the
2320
+ preceding `}`. Add a space between the `@` label and the opening brace (`{`), as
2321
+ well as between the `@catch` and the caught object declaration. If you must use
2322
+ Objective-C exceptions, format them as follows. However, see [Avoid Throwing
2323
+ Exceptions](#Avoid_Throwing_Exceptions) for reasons why you should not be using
2324
+ exceptions.
2325
+
2326
+ ```objectivec
2327
+ // GOOD:
2328
+
2329
+ @try {
2330
+ foo();
2331
+ } @catch (NSException *ex) {
2332
+ bar(ex);
2333
+ } @finally {
2334
+ baz();
2335
+ }
2336
+ ```
2337
+
2338
+ <a id="Function_Length"></a>
2339
+
2340
+ ### Function Length
2341
+
2342
+ Prefer small and focused functions.
2343
+
2344
+ Long functions and methods are occasionally appropriate, so no hard limit is
2345
+ placed on function length. If a function exceeds about 40 lines, think about
2346
+ whether it can be broken up without harming the structure of the program.
2347
+
2348
+ Even if your long function works perfectly now, someone modifying it in a few
2349
+ months may add new behavior. This could result in bugs that are hard to find.
2350
+ Keeping your functions short and simple makes it easier for other people to read
2351
+ and modify your code.
2352
+
2353
+ When updating legacy code, consider also breaking long functions into smaller
2354
+ and more manageable pieces.
2355
+
2356
+ <a id="Vertical_Whitespace"></a>
2357
+
2358
+ ### Vertical Whitespace
2359
+
2360
+ Use vertical whitespace sparingly.
2361
+
2362
+ To allow more code to be easily viewed on a screen, avoid putting blank lines
2363
+ just inside the braces of functions.
2364
+
2365
+ Limit blank lines to one or two between functions and between logical groups of
2366
+ code.
2367
+
2368
+ <a id="Objective-C_Style_Exceptions"></a>
2369
+
2370
+ ## Objective-C Style Exceptions
2371
+
2372
+ <a id="Indicating_style_exceptions"></a>
2373
+
2374
+ ### Indicating style exceptions
2375
+
2376
+ Lines of code that are not expected to adhere to these style recommendations
2377
+ require `// NOLINT` at the end of the line or `// NOLINTNEXTLINE` at the end of
2378
+ the previous line. Sometimes it is required that parts of Objective-C code must
2379
+ ignore these style recommendations (for example code may be machine generated or
2380
+ code constructs are such that its not possible to style correctly).
2381
+
2382
+ A `// NOLINT` comment on that line or `// NOLINTNEXTLINE` on the previous line
2383
+ can be used to indicate to the reader that code is intentionally ignoring style
2384
+ guidelines. In addition these annotations can also be picked up by automated
2385
+ tools such as linters and handle code correctly. Note that there is a single
2386
+ space between `//` and `NOLINT*`.