forked from google/styleguide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
objcguide.xml
1884 lines (1730 loc) · 64.8 KB
/
objcguide.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="styleguide.xsl"?>
<GUIDE title="Google Objective-C Style Guide">
<p align="right">
Revision 2.59
</p>
<div align="right">
<address>
Mike Pinkerton<br/>
Greg Miller <br/>
Dave MacLachlan
</address>
</div>
<OVERVIEW>
<CATEGORY title="Important Note">
<STYLEPOINT title="Displaying Hidden Details in this Guide">
<SUMMARY>
This style guide contains many details that are initially
hidden from view. They are marked by the triangle icon, which you
see here on your left. Click it now.
You should see "Hooray" appear below.
</SUMMARY>
<BODY>
<p>
Hooray! Now you know you can expand points to get more
details. Alternatively, there's an "expand all" at the
top of this document.
</p>
</BODY>
</STYLEPOINT>
</CATEGORY>
<CATEGORY title="Background">
<p>
Objective-C is a very dynamic, object-oriented extension of C. It's
designed to be easy to use and read, while enabling sophisticated
object-oriented design. It is the primary development language for new
applications on Mac OS X and the iPhone.
</p>
<p>
Cocoa is one of the main application frameworks on Mac OS X. It is a
collection of Objective-C classes that provide for rapid development of
full-featured Mac OS X applications.
</p>
<p>
Apple has already written a very good, and widely accepted, coding guide
for Objective-C. Google has also written a similar guide for C++. This
Objective-C guide aims to be a very natural combination of Apple's and
Google's general recommendations. So, before reading this guide, please make
sure you've read:
<ul>
<li>
<a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/index.html">
Apple's Cocoa Coding Guidelines
</a>
</li>
<li>
<div>
<a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml">
Google's Open Source C++ Style Guide
</a>
</div>
</li>
</ul>
</p>
<p>
<em>Note that all things that are banned in Google's C++ guide are also
banned in Objective-C++, unless explicitly noted in this document.</em>
</p>
<p>
The purpose of this document is to describe the Objective-C (and
Objective-C++) coding guidelines and practices that should be used for all
Mac OS X code. Many of these guidelines have evolved and been proven over
time on other projects and teams.
Open-source projects developed by Google
conform to the requirements in this guide.
</p>
<p>
Google has already released open-source code that conforms to these
guidelines as part of the
<a href="http://code.google.com/p/google-toolbox-for-mac/">
Google Toolbox for Mac project
</a>
(abbreviated GTM throughout this document).
Code meant to be shared across different projects is a good candidate to
be included in this repository.
</p>
<p>
Note that this guide is not an Objective-C tutorial. We assume that the
reader is familiar with the language. If you are new to Objective-C or
need a refresher, please read
<a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html">
Programming with Objective-C
</a>.
</p>
</CATEGORY>
</OVERVIEW>
<CATEGORY title="Example">
<p>
They say an example is worth a thousand words so let's start off with an
example that should give you a feel for the style, spacing, naming, etc.
</p>
<p>
An example header file, demonstrating the correct commenting and spacing
for an <code>@interface</code> declaration
</p>
<CODE_SNIPPET>
#import <Foundation/Foundation.h>
// A sample class demonstrating good Objective-C style. All interfaces,
// categories, and protocols (read: all non-trivial top-level declarations
// in a header) MUST be commented. Comments must also be adjacent to the
// object they're documenting.
//
// (no blank line between this comment and the interface)
@interface Foo : NSObject
// Returns an autoreleased instance of Foo. See -initWithBar: for details
// about |bar|.
+ (instancetype)fooWithBar:(NSString *)bar;
// Designated initializer. |bar| is a thing that represents a thing that
// does a thing.
- (instancetype)initWithBar:(NSString *)bar;
// Gets and sets |_bar|.
- (NSString *)bar;
- (void)setBar:(NSString *)bar;
// Does some work with |blah| and returns YES if the work was completed
// successfully, and NO otherwise.
- (BOOL)doWorkWithBlah:(NSString *)blah;
@end
</CODE_SNIPPET>
<p>
An example source file, demonstrating the correct commenting and spacing
for the <code>@implementation</code> of an interface. It also includes the
reference implementations for important methods like getters and setters,
<code>init</code>, and <code>dealloc</code>.
</p>
<CODE_SNIPPET>
#import "Foo.h"
@implementation Foo {
NSString *_bar;
NSString *_foo;
}
+ (instancetype)fooWithBar:(NSString *)bar {
return [[[self alloc] initWithBar:bar] autorelease];
}
// Must always override super's designated initializer.
- (instancetype)init {
return [self initWithBar:nil];
}
- (instancetype)initWithBar:(NSString *)bar {
if ((self = [super init])) {
_bar = [bar copy];
_bam = [[NSString alloc] initWithFormat:@"hi %d", 3];
}
return self;
}
- (void)dealloc {
[_bar release];
[_bam release];
[super dealloc];
}
- (NSString *)bar {
return _bar;
}
- (void)setBar:(NSString *)bar {
[_bar autorelease];
_bar = [bar copy];
}
- (BOOL)doWorkWithBlah:(NSString *)blah {
// ...
return NO;
}
@end
</CODE_SNIPPET>
<p>
Blank lines before and after <code>@interface</code>,
<code>@implementation</code>, and <code>@end</code> are optional. If your
<code>@interface</code> declares instance variables, a blank
line should come after the closing brace (<code>}</code>).
<p>
</p>
Unless an interface or implementation is very short, such as when declaring
a handful of private methods or a bridge class, adding blank lines usually
helps readability.
</p>
</CATEGORY>
<CATEGORY title="Spacing And Formatting">
<STYLEPOINT title="Spaces vs. Tabs">
<SUMMARY>
Use only spaces, and indent 2 spaces at a time.
</SUMMARY>
<BODY>
<p>
We use spaces for indentation. Do not use tabs in your code.
You should set your editor to emit spaces when you hit the tab
key.
</p>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Line Length">
<SUMMARY>
The maximum line length for Objective-C and Objective-C++ files is 100
columns. Projects may opt to use an 80 column limit for consistency with
the C++ style guide.
</SUMMARY>
<BODY>
<p>
You can make violations easier to spot by enabling <i>Preferences >
Text Editing > Page guide at column: 100</i> in Xcode.
</p>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Method Declarations and Definitions">
<SUMMARY>
One space should be used between the <code>-</code> or <code>+</code>
and the return type, and no spacing in the parameter list except between
parameters.
</SUMMARY>
<BODY>
<p>
Methods should look like this:
</p>
<CODE_SNIPPET>
- (void)doSomethingWithString:(NSString *)theString {
...
}
</CODE_SNIPPET>
<p>
The spacing before the asterisk is optional. When adding new code,
be consistent with the surrounding file's style.
</p>
<p>
If you have too many parameters to fit on one line, giving each its
own line is preferred. If multiple lines are used, align each using
the colon before the parameter.
</p>
<CODE_SNIPPET>
- (void)doSomethingWith:(GTMFoo *)theFoo
rect:(NSRect)theRect
interval:(float)theInterval {
...
}
</CODE_SNIPPET>
<p>
When the first keyword is shorter than the others, indent the later
lines by at least four spaces, maintaining colon alignment:
</p>
<CODE_SNIPPET>
- (void)short:(GTMFoo *)theFoo
longKeyword:(NSRect)theRect
evenLongerKeyword:(float)theInterval
error:(NSError **)theError {
...
}
</CODE_SNIPPET>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Method Invocations">
<SUMMARY>
Method invocations should be formatted much like method declarations.
When there's a choice of formatting styles, follow the convention
already used in a given source file.
</SUMMARY>
<BODY>
<p>
Invocations should have all arguments on one line:
</p>
<CODE_SNIPPET>
[myObject doFooWith:arg1 name:arg2 error:arg3];
</CODE_SNIPPET>
<p>
or have one argument per line, with colons aligned:
</p>
<CODE_SNIPPET>
[myObject doFooWith:arg1
name:arg2
error:arg3];
</CODE_SNIPPET>
<p>
Don't use any of these styles:
</p>
<BAD_CODE_SNIPPET>
[myObject doFooWith:arg1 name:arg2 // some lines with >1 arg
error:arg3];
[myObject doFooWith:arg1
name:arg2 error:arg3];
[myObject doFooWith:arg1
name:arg2 // aligning keywords instead of colons
error:arg3];
</BAD_CODE_SNIPPET>
<p>
As with declarations and definitions, when the first keyword is shorter
than the others, indent the later lines by at least four spaces,
maintaining colon alignment:
</p>
<CODE_SNIPPET>
[myObj short:arg1
longKeyword:arg2
evenLongerKeyword:arg3
error:arg4];
</CODE_SNIPPET>
<p>
Invocations containing inlined <a href="#Blocks">blocks</a> may have
their segments left-aligned at a four space indent.
</p>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="@public and @private">
<SUMMARY>
The <code>@public</code> and <code>@private</code> access modifiers
should be indented by 1 space.
</SUMMARY>
<BODY>
<p>
This is similar to <code>public</code>, <code>private</code>, and
<code>protected</code> in C++.
</p>
<CODE_SNIPPET>
@interface MyClass : NSObject {
@public
...
@private
...
}
@end
</CODE_SNIPPET>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Exceptions">
<SUMMARY>
Format exceptions with each <code>@</code> label on its own line and a
space between the <code>@</code> label and the opening brace
(<code>{</code>), as well as between the <code>@catch</code> and the
caught object declaration.
</SUMMARY>
<BODY>
<p>
If you must use Obj-C exceptions, format them as follows. However, see
<a href="#Avoid_Throwing_Exceptions">Avoid Throwing Exceptions</a> for
reasons why you <b>should not</b> be using exceptions.
</p>
<CODE_SNIPPET>
@try {
foo();
}
@catch (NSException *ex) {
bar(ex);
}
@finally {
baz();
}
</CODE_SNIPPET>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Protocols">
<SUMMARY>
There should not be a space between the type identifier and the name
of the protocol encased in angle brackets.
</SUMMARY>
<BODY>
<p>
This applies to class declarations, instance variables, and method
declarations. For example:
</p>
<CODE_SNIPPET>
@interface MyProtocoledClass : NSObject<NSWindowDelegate> {
@private
id<MyFancyDelegate> _delegate;
}
- (void)setDelegate:(id<MyFancyDelegate>)aDelegate;
@end
</CODE_SNIPPET>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Blocks">
<SUMMARY>
Code inside blocks should be indented four spaces.
</SUMMARY>
<BODY>
<p>
There are several appropriate style rules, depending on how long the
block is:
</p>
<ul>
<li>If the block can fit on one line, no wrapping is necessary.</li>
<li>
If it has to wrap, the closing brace should line up with the first
character of the line on which the block is declared.
</li>
<li>Code within the block should be indented four spaces.</li>
<li>
If the block is large, e.g. more than 20 lines, it is recommended to
move it out-of-line into a local variable.
</li>
<li>
If the block takes no parameters, there are no spaces between the
characters <code>^{</code>. If the block takes parameters, there is no
space between the <code>^(</code> characters, but there is one space
between the <code>) {</code> characters.
</li>
<li>
Invocations containing inlined blocks may have their segments
left-aligned at a four-space indent. This helps when invocations
contain multiple inlined blocks.
</li>
<li>
Two space indents inside blocks are also allowed, but should only
be used when it's consistent with the rest of the project's code.
</li>
</ul>
<CODE_SNIPPET>
// The entire block fits on one line.
[operation setCompletionBlock:^{ [self onOperationDone]; }];
// The block can be put on a new line, indented four spaces, with the
// closing brace aligned with the first character of the line on which
// block was declared.
[operation setCompletionBlock:^{
[self.delegate newDataAvailable];
}];
// Using a block with a C API follows the same alignment and spacing
// rules as with Objective-C.
dispatch_async(_fileIOQueue, ^{
NSString* path = [self sessionFilePath];
if (path) {
// ...
}
});
// An example where the parameter wraps and the block declaration fits
// on the same line. Note the spacing of |^(SessionWindow *window) {|
// compared to |^{| above.
[[SessionService sharedService]
loadWindowWithCompletionBlock:^(SessionWindow *window) {
if (window) {
[self windowDidLoad:window];
} else {
[self errorLoadingWindow];
}
}];
// An example where the parameter wraps and the block declaration does
// not fit on the same line as the name.
[[SessionService sharedService]
loadWindowWithCompletionBlock:
^(SessionWindow *window) {
if (window) {
[self windowDidLoad:window];
} else {
[self errorLoadingWindow];
}
}];
// Large blocks can be declared out-of-line.
void (^largeBlock)(void) = ^{
// ...
};
[_operationQueue addOperationWithBlock:largeBlock];
// An example with multiple inlined blocks in one invocation.
[myObject doSomethingWith:arg1
firstBlock:^(Foo *a) {
// ...
}
secondBlock:^(Bar *b) {
// ...
}];
</CODE_SNIPPET>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Container Literals">
<SUMMARY>
For projects using Xcode 4.4 or later and clang, the use of container
(array and dictionary) literals is encouraged. If split across multiple
lines, the contents should be indented two spaces.
</SUMMARY>
<BODY>
<p>
If the collection fits on one line, put a single space after the opening
and before the closing brackets.
</p>
<CODE_SNIPPET>
NSArray* array = @[ [foo description], @"Another String", [bar description] ];
NSDictionary* dict = @{ NSForegroundColorAttributeName : [NSColor redColor] };
</CODE_SNIPPET>
<p>
Not:
</p>
<BAD_CODE_SNIPPET>
NSArray* array = @[[foo description], [bar description]];
NSDictionary* dict = @{NSForegroundColorAttributeName: [NSColor redColor]};
</BAD_CODE_SNIPPET>
<p>
If the collection spans more than a single line, place the opening
bracket on the same line as the declaration, indent the body by two
spaces, and place the closing bracket on a new line that is indented to
the same level as the opening bracket.
</p>
<CODE_SNIPPET>
NSArray* array = @[
@"This",
@"is",
@"an",
@"array"
];
NSDictionary* dictionary = @{
NSFontAttributeName : [NSFont fontWithName:@"Helvetica-Bold" size:12],
NSForegroundColorAttributeName : fontColor
};
</CODE_SNIPPET>
<p>
For dictionary literals, there should be one space before the colon and
at least one space after it (to optionally align the values).
</p>
<CODE_SNIPPET>
NSDictionary* option1 = @{
NSFontAttributeName : [NSFont fontWithName:@"Helvetica-Bold" size:12],
NSForegroundColorAttributeName : fontColor
};
NSDictionary* option2 = @{
NSFontAttributeName : [NSFont fontWithName:@"Arial" size:12],
NSForegroundColorAttributeName : fontColor
};
</CODE_SNIPPET>
<p>
The following are all incorrect:
</p>
<BAD_CODE_SNIPPET>
// There should be a space before the colon.
NSDictionary* wrong = @{
AKey: @"b",
BLongerKey: @"c",
};
// The items should each be on a new line, or the entire expression
// should fit on one line.
NSDictionary* alsoWrong= @{ AKey : @"a",
BLongerKey : @"b" };
// There should be no variable space before the colon, only after.
NSDictionary* stillWrong = @{
AKey : @"b",
BLongerKey : @"c",
};
</BAD_CODE_SNIPPET>
</BODY>
</STYLEPOINT>
</CATEGORY>
<CATEGORY title="Naming">
<p>
Naming rules are very important in maintainable code. Objective-C method
names tend to be very long, but this has the benefit that a block of code
can almost read like prose, thus rendering many comments unnecessary. </p>
<p> When writing pure Objective-C code, we mostly follow standard <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html">Objective-C
naming rules</a>. These naming guidelines may differ
significantly from those outlined in the C++ style guide. For example,
Google's C++ style guide recommends the use of underscores between words
in variable names, whereas this guide recommends the use of intercaps,
which is standard in the Objective-C community.
</p>
<p>
Any class, category, method, or variable name may use all capitals for
<a href="http://en.wikipedia.org/wiki/Initialism">initialisms</a>
within the name. This follows Apple's standard of using all capitals
within a name for initialisms such as URL, TIFF, and EXIF.
</p>
<p>
When writing Objective-C++, however, things are not so cut and dry. Many
projects need to implement cross-platform C++ APIs with some Objective-C
or Cocoa, or bridge between a C++ back-end and a native Cocoa front-end.
This leads to situations where the two guides are directly at odds.
</p>
<p>
Our solution is that the style follows that of the method/function being
implemented. If you're in an <code>@implementation</code> block, use the
Objective-C naming rules. If you're implementing a method for a C++
<code>class</code>, use the C++ naming rules. This avoids the situation
where instance variable and local variable naming rules are mixed within a
single function, which would be a serious detriment to readability.
</p>
<STYLEPOINT title="File Names">
<SUMMARY>
File names should reflect the name of the class implementation that
they contain—including case. Follow the convention that your
project
uses.
</SUMMARY>
<BODY>
<p>
File extensions should be as follows:
</p>
<table>
<tr>
<td><code>.h</code></td>
<td>C/C++/Objective-C header file</td>
</tr>
<tr>
<td><code>.m</code></td>
<td>Objective-C implementation file</td>
</tr>
<tr>
<td><code>.mm</code></td>
<td>Objective-C++ implementation file</td>
</tr>
<tr>
<td><code>.cc</code></td>
<td>Pure C++ implementation file</td>
</tr>
<tr>
<td><code>.c</code></td>
<td>C implementation file</td>
</tr>
</table>
<p>
File names for categories should include the name of the class being
extended, e.g. <code>GTMNSString+Utils.h</code> or
<code>GTMNSTextView+Autocomplete.h</code>
</p>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Objective-C++">
<SUMMARY>
Within a source file, Objective-C++ follows the style of the
function/method you're implementing.
</SUMMARY>
<BODY>
<p>
In order to minimize clashes between the differing naming styles when
mixing Cocoa/Objective-C and C++, follow the style of the method being
implemented. If you're in an <code>@implementation</code> block, use
the Objective-C naming rules. If you're implementing a method for a
C++ <code>class</code>, use the C++ naming rules.
</p>
<CODE_SNIPPET>
// file: cross_platform_header.h
class CrossPlatformAPI {
public:
...
int DoSomethingPlatformSpecific(); // impl on each platform
private:
int an_instance_var_;
};
// file: mac_implementation.mm
#include "cross_platform_header.h"
// A typical Objective-C class, using Objective-C naming.
@interface MyDelegate : NSObject {
@private
int _instanceVar;
CrossPlatformAPI* _backEndObject;
}
- (void)respondToSomething:(id)something;
@end
@implementation MyDelegate
- (void)respondToSomething:(id)something {
// bridge from Cocoa through our C++ backend
_instanceVar = _backEndObject->DoSomethingPlatformSpecific();
NSString* tempString = [NSString stringWithFormat:@"%d", _instanceVar];
NSLog(@"%@", tempString);
}
@end
// The platform-specific implementation of the C++ class, using
// C++ naming.
int CrossPlatformAPI::DoSomethingPlatformSpecific() {
NSString* temp_string = [NSString stringWithFormat:@"%d", an_instance_var_];
NSLog(@"%@", temp_string);
return [temp_string intValue];
}
</CODE_SNIPPET>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Class Names">
<SUMMARY>
Class names (along with category and protocol names) should start as
uppercase and use mixed case to delimit words.
</SUMMARY>
<BODY>
<p>
When designing code to be shared across multiple applications,
prefixes are acceptable and recommended (e.g. <code>GTMSendMessage</code>).
Prefixes are also recommended for classes of large applications that
depend on external libraries.
</p>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Category Names">
<SUMMARY>
Category names should start with a 2 or 3 character prefix
identifying the category as part of a project or open for general
use. The category name should incorporate the name of the class it's
extending.
</SUMMARY>
<BODY>
<p>
For example, if we want to create a category on <code>NSString</code>
for parsing, we would put the category in a file named
<code>GTMNSString+Parsing.h</code>, and the category itself would be
named <code>GTMStringParsingAdditions</code> (yes, we know the file
name and the category name do not match, but this file could have many
separate categories related to parsing). Methods in that category
should share the prefix (<code>gtm_myCategoryMethodOnAString:</code>)
in order to prevent collisions in Objective-C which only has a single
namespace. If the code isn't meant to be shared and/or doesn't run in
a different address-space, the method naming isn't quite as
important.
</p>
<p>
There should be a single space between the class name and the opening
parenthesis of the category.
</p>
<CODE_SNIPPET>
// Extending a framework class:
@interface NSString (GTMStringParsingAdditions)
- (NSString *)gtm_foobarString;
@end
// Making your methods and properties private:
@interface FoobarViewController ()
@property(nonatomic, retain) NSView *dongleView;
- (void)performLayout;
@end
</CODE_SNIPPET>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Objective-C Method Names">
<SUMMARY>
Method names should start as lowercase and then use mixed case.
Each named parameter should also start as lowercase.
</SUMMARY>
<BODY>
<p>
The method name should read like a sentence if possible, meaning you
should choose parameter names that flow with the method name. (e.g.
<code>convertPoint:fromRect:</code> or
<code>replaceCharactersInRange:withString:</code>). See <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282-BCIGIJJF">Apple's
Guide to Naming Methods</a> for more details.
</p>
<p>
Accessor methods should be named the same as the variable they're
"getting", but they should <em>not</em> be prefixed with the word
"get". For example:
<BAD_CODE_SNIPPET>
- (id)getDelegate; // AVOID
</BAD_CODE_SNIPPET>
<CODE_SNIPPET>
- (id)delegate; // GOOD
</CODE_SNIPPET>
</p>
<p>
This is for Objective-C methods only. C++ method names and functions
continue to follow the rules set in the C++ style guide.
</p>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Variable Names">
<SUMMARY>
Variables names start with a lowercase and use mixed case to delimit
words. Instance variables have leading underscores. For example:
<var>myLocalVariable</var>, <var>_myInstanceVariable</var>.
</SUMMARY>
<BODY>
<SUBSECTION title="Common Variable Names">
<p>
Do <em>not</em> use Hungarian notation for syntactic attributes,
such as the static type of a variable (int or pointer). Give as
descriptive a name as possible, within reason. Don't worry about
saving horizontal space as it is far more important to make your
code immediately understandable by a new reader. For example:
</p>
<BAD_CODE_SNIPPET>
int w;
int nerr;
int nCompConns;
tix = [[NSMutableArray alloc] init];
obj = [someObject object];
p = [network port];
</BAD_CODE_SNIPPET>
<CODE_SNIPPET>
int numErrors;
int numCompletedConnections;
tickets = [[NSMutableArray alloc] init];
userInfo = [someObject object];
port = [network port];
</CODE_SNIPPET>
</SUBSECTION>
<SUBSECTION title="Instance Variables">
<p>
Instance variables are mixed case and should be prefixed with an
underscore e.g. <var>_usernameTextField</var>. Note that historically
the convention was to put the underscore at the end of the name, and
projects may opt to continue using trailing underscores in new code
in order to maintain consistency within their codebase (see the
Historical Notes section). It is recommended you leave old
code as-is, unless doing so would create inconsistency within a class.
</p>
</SUBSECTION>
<SUBSECTION title="Constants">
<p>
Constant names (#defines, enums, const local variables, etc.) should
start with a lowercase <var>k</var> and then use mixed case to
delimit words. For example:
</p>
<CODE_SNIPPET>
const int kNumberOfFiles = 12;
NSString *const kUserKey = @"kUserKey";
enum DisplayTinge {
kDisplayTingeGreen = 1,
kDisplayTingeBlue = 2
};
</CODE_SNIPPET>
<p>
Because Objective-C does not provide namespacing, constants with global
scope should have an appropriate prefix to minimize the chance of name
collision, typically like <var>kClassNameFoo</var>.
</p>
</SUBSECTION>
</BODY>
</STYLEPOINT>
</CATEGORY>
<CATEGORY title="Comments">
<p>
Though a pain to write, they are absolutely vital to keeping our code
readable. The following rules describe what you should comment and where.
But remember: while comments are very important, the best code is
self-documenting. Giving sensible names to types and variables is much
better than using obscure names and then trying to explain them through
comments.
</p>
<p>
When 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!
</p>
<p>
Remember that all of the rules and conventions listed in the C++ Style
Guide are in effect here, with a few additional points, below.
</p>
<STYLEPOINT title="File Comments">
<SUMMARY>
A file may optionally start with a description of its contents.
</SUMMARY>
<BODY>
<p>
Every file should contain the following items, in order:
<ul>
<li>license boilerplate if neccessary. Choose the appropriate
boilerplate for the license used by the project (e.g.
Apache 2.0, BSD, LGPL, GPL).</li>
<li>a basic description of the contents of the file if necessary.</li>
</ul>
</p>
<p>
If you make significant changes to a file with an author line,
consider deleting the author line since revision history already
provides a more detailed and accurate record of authorship.
</p>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Declaration Comments">
<SUMMARY>
Every interface, category, and protocol declaration should have an
accompanying comment describing its purpose and how it fits into the
larger picture.
</SUMMARY>
<BODY>
<CODE_SNIPPET>
// A delegate for NSApplication to handle notifications about app
// launch and shutdown. Owned by the main app controller.
@interface MyAppDelegate : NSObject {
...
}
@end
</CODE_SNIPPET>
<p>
If you have already described an interface in detail in the
comments at the top of your file feel free to simply state
"See comment at top of file for a complete description", but
be sure to have some sort of comment.
</p>
<p>
Additionally, each method in the public interface should have a
comment explaining its function, arguments, return value, and any
side effects.
</p>
<p>
Document the synchronization assumptions the class makes, if
any. If an instance of the class can be accessed by multiple
threads, take extra care to document the rules and invariants
surrounding multithreaded use.
</p>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Implementation Comments">
<SUMMARY>
Use vertical bars to quote variable names and symbols in comments rather
than quotes or naming the symbol inline.
</SUMMARY>
<BODY>
<p>
This helps eliminate ambiguity, especially when the symbol is a common
word that might make the sentence read like it was poorly constructed.
E.g. for a symbol "count":
</p>
<CODE_SNIPPET>
// Sometimes we need |count| to be less than zero.
</CODE_SNIPPET>
<p>
or when quoting something which already contains quotes
</p>
<CODE_SNIPPET>
// Remember to call |StringWithoutSpaces("foo bar baz")|
</CODE_SNIPPET>
</BODY>