├── .gitignore └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | .DS_Store 3 | */build/* 4 | *.pbxuser 5 | !default.pbxuser 6 | *.mode1v3 7 | !default.mode1v3 8 | *.mode2v3 9 | !default.mode2v3 10 | *.perspectivev3 11 | !default.perspectivev3 12 | xcuserdata 13 | profile 14 | *.moved-aside 15 | DerivedData 16 | .idea/ 17 | *.hmap 18 | *.xccheckout 19 | 20 | #CocoaPods 21 | Pods 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The official raywenderlich.com Objective-C style guide. 2 | 3 | This style guide outlines the coding conventions for raywenderlich.com. 4 | 5 | ## Introduction 6 | 7 | The reason we made this style guide was so that we could keep the code in our books, tutorials, and starter kits nice and consistent - even though we have many different authors working on the books. 8 | 9 | This style guide is different from other Objective-C style guides you may see, because the focus is centered on readability for print and the web. Many of the decisions were made with an eye toward conserving space for print, easy legibility, and tutorial writing. 10 | 11 | ## Credits 12 | 13 | The creation of this style guide was a collaborative effort from various raywenderlich.com team members under the direction of Nicholas Waynik. The team includes: [Soheil Moayedi Azarpour](https://github.com/moayes), [Ricardo Rendon Cepeda](https://github.com/ricardo-rendoncepeda), [Tony Dahbura](https://github.com/tdahbura), [Colin Eberhardt](https://github.com/ColinEberhardt), [Matt Galloway](https://github.com/mattjgalloway), [Greg Heo](https://github.com/gregheo), [Matthijs Hollemans](https://github.com/hollance), [Christopher LaPollo](https://github.com/elephantronic), [Saul Mora](https://github.com/casademora), [Andy Pereira](https://github.com/macandyp), [Mic Pringle](https://github.com/micpringle), [Pietro Rea](https://github.com/pietrorea), [Cesare Rocchi](https://github.com/funkyboy), [Marin Todorov](https://github.com/icanzilb), [Nicholas Waynik](https://github.com/ndubbs), and [Ray Wenderlich](https://github.com/raywenderlich) 14 | 15 | We would like to thank the creators of the [New York Times](https://github.com/NYTimes/objective-c-style-guide) and [Robots & Pencils'](https://github.com/RobotsAndPencils/objective-c-style-guide) Objective-C Style Guides. These two style guides provided a solid starting point for this guide to be created and based upon. 16 | 17 | ## Background 18 | 19 | Here are some of the documents from Apple that informed the style guide. If something isn't mentioned here, it's probably covered in great detail in one of these: 20 | 21 | * [The Objective-C Programming Language](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Introduction/introObjectiveC.html) 22 | * [Cocoa Fundamentals Guide](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/Introduction/Introduction.html) 23 | * [Coding Guidelines for Cocoa](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html) 24 | * [iOS App Programming Guide](http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/Introduction/Introduction.html) 25 | 26 | ## Table of Contents 27 | 28 | * [Language](#language) 29 | * [Code Organization](#code-organization) 30 | * [Spacing](#spacing) 31 | * [Comments](#comments) 32 | * [Naming](#naming) 33 | * [Underscores](#underscores) 34 | * [Methods](#methods) 35 | * [Variables](#variables) 36 | * [Property Attributes](#property-attributes) 37 | * [Dot-Notation Syntax](#dot-notation-syntax) 38 | * [Literals](#literals) 39 | * [Constants](#constants) 40 | * [Enumerated Types](#enumerated-types) 41 | * [Case Statements](#case-statements) 42 | * [Private Properties](#private-properties) 43 | * [Booleans](#booleans) 44 | * [Conditionals](#conditionals) 45 | * [Ternary Operator](#ternary-operator) 46 | * [Init Methods](#init-methods) 47 | * [Class Constructor Methods](#class-constructor-methods) 48 | * [CGRect Functions](#cgrect-functions) 49 | * [Golden Path](#golden-path) 50 | * [Error handling](#error-handling) 51 | * [Singletons](#singletons) 52 | * [Line Breaks](#line-breaks) 53 | * [Smiley Face](#smiley-face) 54 | * [Xcode Project](#xcode-project) 55 | 56 | 57 | ## Language 58 | 59 | US English should be used. 60 | 61 | **Preferred:** 62 | ```objc 63 | UIColor *myColor = [UIColor whiteColor]; 64 | ``` 65 | 66 | **Not Preferred:** 67 | ```objc 68 | UIColor *myColour = [UIColor whiteColor]; 69 | ``` 70 | 71 | 72 | ## Code Organization 73 | 74 | Use `#pragma mark -` to categorize methods in functional groupings and protocol/delegate implementations following this general structure. 75 | 76 | ```objc 77 | #pragma mark - Lifecycle 78 | 79 | - (instancetype)init {} 80 | - (void)dealloc {} 81 | - (void)viewDidLoad {} 82 | - (void)viewWillAppear:(BOOL)animated {} 83 | - (void)didReceiveMemoryWarning {} 84 | 85 | #pragma mark - Custom Accessors 86 | 87 | - (void)setCustomProperty:(id)value {} 88 | - (id)customProperty {} 89 | 90 | #pragma mark - IBActions 91 | 92 | - (IBAction)submitData:(id)sender {} 93 | 94 | #pragma mark - Public 95 | 96 | - (void)publicMethod {} 97 | 98 | #pragma mark - Private 99 | 100 | - (void)privateMethod {} 101 | 102 | #pragma mark - Protocol conformance 103 | #pragma mark - UITextFieldDelegate 104 | #pragma mark - UITableViewDataSource 105 | #pragma mark - UITableViewDelegate 106 | 107 | #pragma mark - NSCopying 108 | 109 | - (id)copyWithZone:(NSZone *)zone {} 110 | 111 | #pragma mark - NSObject 112 | 113 | - (NSString *)description {} 114 | ``` 115 | 116 | ## Spacing 117 | 118 | * Indent using 2 spaces (this conserves space in print and makes line wrapping less likely). Never indent with tabs. Be sure to set this preference in Xcode. 119 | * Method braces and other braces (`if`/`else`/`switch`/`while` etc.) always open on the same line as the statement but close on a new line. 120 | 121 | **Preferred:** 122 | ```objc 123 | if (user.isHappy) { 124 | //Do something 125 | } else { 126 | //Do something else 127 | } 128 | ``` 129 | 130 | **Not Preferred:** 131 | ```objc 132 | if (user.isHappy) 133 | { 134 | //Do something 135 | } 136 | else { 137 | //Do something else 138 | } 139 | ``` 140 | 141 | * There should be exactly one blank line between methods to aid in visual clarity and organization. Whitespace within methods should separate functionality, but often there should probably be new methods. 142 | * Prefer using auto-synthesis. But if necessary, `@synthesize` and `@dynamic` should each be declared on new lines in the implementation. 143 | * Colon-aligning method invocation should often be avoided. There are cases where a method signature may have >= 3 colons and colon-aligning makes the code more readable. Please do **NOT** however colon align methods containing blocks because Xcode's indenting makes it illegible. 144 | 145 | **Preferred:** 146 | 147 | ```objc 148 | // blocks are easily readable 149 | [UIView animateWithDuration:1.0 animations:^{ 150 | // something 151 | } completion:^(BOOL finished) { 152 | // something 153 | }]; 154 | ``` 155 | 156 | **Not Preferred:** 157 | 158 | ```objc 159 | // colon-aligning makes the block indentation hard to read 160 | [UIView animateWithDuration:1.0 161 | animations:^{ 162 | // something 163 | } 164 | completion:^(BOOL finished) { 165 | // something 166 | }]; 167 | ``` 168 | 169 | ## Comments 170 | 171 | When they are needed, comments should be used to explain **why** a particular piece of code does something. Any comments that are used must be kept up-to-date or deleted. 172 | 173 | Block comments should generally be avoided, as code should be as self-documenting as possible, with only the need for intermittent, few-line explanations. *Exception: This does not apply to those comments used to generate documentation.* 174 | 175 | ## Naming 176 | 177 | Apple naming conventions should be adhered to wherever possible, especially those related to [memory management rules](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html) ([NARC](http://stackoverflow.com/a/2865194/340508)). 178 | 179 | Long, descriptive method and variable names are good. 180 | 181 | **Preferred:** 182 | 183 | ```objc 184 | UIButton *settingsButton; 185 | ``` 186 | 187 | **Not Preferred:** 188 | 189 | ```objc 190 | UIButton *setBut; 191 | ``` 192 | 193 | A three letter prefix should always be used for class names and constants, however may be omitted for Core Data entity names. For any official raywenderlich.com books, starter kits, or tutorials, the prefix 'RWT' should be used. 194 | 195 | Constants should be camel-case with all words capitalized and prefixed by the related class name for clarity. 196 | 197 | **Preferred:** 198 | 199 | ```objc 200 | static NSTimeInterval const RWTTutorialViewControllerNavigationFadeAnimationDuration = 0.3; 201 | ``` 202 | 203 | **Not Preferred:** 204 | 205 | ```objc 206 | static NSTimeInterval const fadetime = 1.7; 207 | ``` 208 | 209 | Properties should be camel-case with the leading word being lowercase. Use auto-synthesis for properties rather than manual @synthesize statements unless you have good reason. 210 | 211 | **Preferred:** 212 | 213 | ```objc 214 | @property (strong, nonatomic) NSString *descriptiveVariableName; 215 | ``` 216 | 217 | **Not Preferred:** 218 | 219 | ```objc 220 | id varnm; 221 | ``` 222 | 223 | ### Underscores 224 | 225 | When using properties, instance variables should always be accessed and mutated using `self.`. This means that all properties will be visually distinct, as they will all be prefaced with `self.`. 226 | 227 | An exception to this: inside initializers, the backing instance variable (i.e. _variableName) should be used directly to avoid any potential side effects of the getters/setters. 228 | 229 | Local variables should not contain underscores. 230 | 231 | ## Methods 232 | 233 | In method signatures, there should be a space after the method type (-/+ symbol). There should be a space between the method segments (matching Apple's style). Always include a keyword and be descriptive with the word before the argument which describes the argument. 234 | 235 | The usage of the word "and" is reserved. It should not be used for multiple parameters as illustrated in the `initWithWidth:height:` example below. 236 | 237 | **Preferred:** 238 | ```objc 239 | - (void)setExampleText:(NSString *)text image:(UIImage *)image; 240 | - (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag; 241 | - (id)viewWithTag:(NSInteger)tag; 242 | - (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height; 243 | ``` 244 | 245 | **Not Preferred:** 246 | 247 | ```objc 248 | -(void)setT:(NSString *)text i:(UIImage *)image; 249 | - (void)sendAction:(SEL)aSelector :(id)anObject :(BOOL)flag; 250 | - (id)taggedView:(NSInteger)tag; 251 | - (instancetype)initWithWidth:(CGFloat)width andHeight:(CGFloat)height; 252 | - (instancetype)initWith:(int)width and:(int)height; // Never do this. 253 | ``` 254 | 255 | ## Variables 256 | 257 | Variables should be named as descriptively as possible. Single letter variable names should be avoided except in `for()` loops. 258 | 259 | Asterisks indicating pointers belong with the variable, e.g., `NSString *text` not `NSString* text` or `NSString * text`, except in the case of constants. 260 | 261 | [Private properties](#private-properties) should be used in place of instance variables whenever possible. Although using instance variables is a valid way of doing things, by agreeing to prefer properties our code will be more consistent. 262 | 263 | Direct access to instance variables that 'back' properties should be avoided except in initializer methods (`init`, `initWithCoder:`, etc…), `dealloc` methods and within custom setters and getters. For more information on using Accessor Methods in Initializer Methods and dealloc, see [here](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html#//apple_ref/doc/uid/TP40004447-SW6). 264 | 265 | **Preferred:** 266 | 267 | ```objc 268 | @interface RWTTutorial : NSObject 269 | 270 | @property (strong, nonatomic) NSString *tutorialName; 271 | 272 | @end 273 | ``` 274 | 275 | **Not Preferred:** 276 | 277 | ```objc 278 | @interface RWTTutorial : NSObject { 279 | NSString *tutorialName; 280 | } 281 | ``` 282 | 283 | 284 | ## Property Attributes 285 | 286 | Property attributes should be explicitly listed, and will help new programmers when reading the code. The order of properties should be storage then atomicity, which is consistent with automatically generated code when connecting UI elements from Interface Builder. 287 | 288 | **Preferred:** 289 | 290 | ```objc 291 | @property (weak, nonatomic) IBOutlet UIView *containerView; 292 | @property (strong, nonatomic) NSString *tutorialName; 293 | ``` 294 | 295 | **Not Preferred:** 296 | 297 | ```objc 298 | @property (nonatomic, weak) IBOutlet UIView *containerView; 299 | @property (nonatomic) NSString *tutorialName; 300 | ``` 301 | 302 | Properties with mutable counterparts (e.g. NSString) should prefer `copy` instead of `strong`. 303 | Why? Even if you declared a property as `NSString` somebody might pass in an instance of an `NSMutableString` and then change it without you noticing that. 304 | 305 | **Preferred:** 306 | 307 | ```objc 308 | @property (copy, nonatomic) NSString *tutorialName; 309 | ``` 310 | 311 | **Not Preferred:** 312 | 313 | ```objc 314 | @property (strong, nonatomic) NSString *tutorialName; 315 | ``` 316 | 317 | ## Dot-Notation Syntax 318 | 319 | Dot syntax is purely a convenient wrapper around accessor method calls. When you use dot syntax, the property is still accessed or changed using getter and setter methods. Read more [here](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html) 320 | 321 | Dot-notation should **always** be used for accessing and mutating properties, as it makes code more concise. Bracket notation is preferred in all other instances. 322 | 323 | **Preferred:** 324 | ```objc 325 | NSInteger arrayCount = [self.array count]; 326 | view.backgroundColor = [UIColor orangeColor]; 327 | [UIApplication sharedApplication].delegate; 328 | ``` 329 | 330 | **Not Preferred:** 331 | ```objc 332 | NSInteger arrayCount = self.array.count; 333 | [view setBackgroundColor:[UIColor orangeColor]]; 334 | UIApplication.sharedApplication.delegate; 335 | ``` 336 | 337 | ## Literals 338 | 339 | `NSString`, `NSDictionary`, `NSArray`, and `NSNumber` literals should be used whenever creating immutable instances of those objects. Pay special care that `nil` values can not be passed into `NSArray` and `NSDictionary` literals, as this will cause a crash. 340 | 341 | **Preferred:** 342 | 343 | ```objc 344 | NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"]; 345 | NSDictionary *productManagers = @{@"iPhone": @"Kate", @"iPad": @"Kamal", @"Mobile Web": @"Bill"}; 346 | NSNumber *shouldUseLiterals = @YES; 347 | NSNumber *buildingStreetNumber = @10018; 348 | ``` 349 | 350 | **Not Preferred:** 351 | 352 | ```objc 353 | NSArray *names = [NSArray arrayWithObjects:@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul", nil]; 354 | NSDictionary *productManagers = [NSDictionary dictionaryWithObjectsAndKeys: @"Kate", @"iPhone", @"Kamal", @"iPad", @"Bill", @"Mobile Web", nil]; 355 | NSNumber *shouldUseLiterals = [NSNumber numberWithBool:YES]; 356 | NSNumber *buildingStreetNumber = [NSNumber numberWithInteger:10018]; 357 | ``` 358 | 359 | ## Constants 360 | 361 | Constants are preferred over in-line string literals or numbers, as they allow for easy reproduction of commonly used variables and can be quickly changed without the need for find and replace. Constants should be declared as `static` constants and not `#define`s unless explicitly being used as a macro. 362 | 363 | **Preferred:** 364 | 365 | ```objc 366 | static NSString * const RWTAboutViewControllerCompanyName = @"RayWenderlich.com"; 367 | 368 | static CGFloat const RWTImageThumbnailHeight = 50.0; 369 | ``` 370 | 371 | **Not Preferred:** 372 | 373 | ```objc 374 | #define CompanyName @"RayWenderlich.com" 375 | 376 | #define thumbnailHeight 2 377 | ``` 378 | 379 | ## Enumerated Types 380 | 381 | When using `enum`s, it is recommended to use the new fixed underlying type specification because it has stronger type checking and code completion. The SDK now includes a macro to facilitate and encourage use of fixed underlying types: `NS_ENUM()` 382 | 383 | **For Example:** 384 | 385 | ```objc 386 | typedef NS_ENUM(NSInteger, RWTLeftMenuTopItemType) { 387 | RWTLeftMenuTopItemMain, 388 | RWTLeftMenuTopItemShows, 389 | RWTLeftMenuTopItemSchedule 390 | }; 391 | ``` 392 | 393 | You can also make explicit value assignments (showing older k-style constant definition): 394 | 395 | ```objc 396 | typedef NS_ENUM(NSInteger, RWTGlobalConstants) { 397 | RWTPinSizeMin = 1, 398 | RWTPinSizeMax = 5, 399 | RWTPinCountMin = 100, 400 | RWTPinCountMax = 500, 401 | }; 402 | ``` 403 | 404 | Older k-style constant definitions should be **avoided** unless writing CoreFoundation C code (unlikely). 405 | 406 | **Not Preferred:** 407 | 408 | ```objc 409 | enum GlobalConstants { 410 | kMaxPinSize = 5, 411 | kMaxPinCount = 500, 412 | }; 413 | ``` 414 | 415 | 416 | ## Case Statements 417 | 418 | Braces are not required for case statements, unless enforced by the complier. 419 | When a case contains more than one line, braces should be added. 420 | 421 | ```objc 422 | switch (condition) { 423 | case 1: 424 | // ... 425 | break; 426 | case 2: { 427 | // ... 428 | // Multi-line example using braces 429 | break; 430 | } 431 | case 3: 432 | // ... 433 | break; 434 | default: 435 | // ... 436 | break; 437 | } 438 | 439 | ``` 440 | 441 | There are times when the same code can be used for multiple cases, and a fall-through should be used. A fall-through is the removal of the 'break' statement for a case thus allowing the flow of execution to pass to the next case value. A fall-through should be commented for coding clarity. 442 | 443 | ```objc 444 | switch (condition) { 445 | case 1: 446 | // ** fall-through! ** 447 | case 2: 448 | // code executed for values 1 and 2 449 | break; 450 | default: 451 | // ... 452 | break; 453 | } 454 | 455 | ``` 456 | 457 | When using an enumerated type for a switch, 'default' is not needed. For example: 458 | 459 | ```objc 460 | RWTLeftMenuTopItemType menuType = RWTLeftMenuTopItemMain; 461 | 462 | switch (menuType) { 463 | case RWTLeftMenuTopItemMain: 464 | // ... 465 | break; 466 | case RWTLeftMenuTopItemShows: 467 | // ... 468 | break; 469 | case RWTLeftMenuTopItemSchedule: 470 | // ... 471 | break; 472 | } 473 | ``` 474 | 475 | 476 | ## Private Properties 477 | 478 | Private properties should be declared in class extensions (anonymous categories) in the implementation file of a class. Named categories (such as `RWTPrivate` or `private`) should never be used unless extending another class. The Anonymous category can be shared/exposed for testing using the +Private.h file naming convention. 479 | 480 | **For Example:** 481 | 482 | ```objc 483 | @interface RWTDetailViewController () 484 | 485 | @property (strong, nonatomic) GADBannerView *googleAdView; 486 | @property (strong, nonatomic) ADBannerView *iAdView; 487 | @property (strong, nonatomic) UIWebView *adXWebView; 488 | 489 | @end 490 | ``` 491 | 492 | ## Booleans 493 | 494 | Objective-C uses `YES` and `NO`. Therefore `true` and `false` should only be used for CoreFoundation, C or C++ code. Since `nil` resolves to `NO` it is unnecessary to compare it in conditions. Never compare something directly to `YES`, because `YES` is defined to 1 and a `BOOL` can be up to 8 bits. 495 | 496 | This allows for more consistency across files and greater visual clarity. 497 | 498 | **Preferred:** 499 | 500 | ```objc 501 | if (someObject) {} 502 | if (![anotherObject boolValue]) {} 503 | ``` 504 | 505 | **Not Preferred:** 506 | 507 | ```objc 508 | if (someObject == nil) {} 509 | if ([anotherObject boolValue] == NO) {} 510 | if (isAwesome == YES) {} // Never do this. 511 | if (isAwesome == true) {} // Never do this. 512 | ``` 513 | 514 | If the name of a `BOOL` property is expressed as an adjective, the property can omit the “is” prefix but specifies the conventional name for the get accessor, for example: 515 | 516 | ```objc 517 | @property (assign, getter=isEditable) BOOL editable; 518 | ``` 519 | Text and example taken from the [Cocoa Naming Guidelines](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingIvarsAndTypes.html#//apple_ref/doc/uid/20001284-BAJGIIJE). 520 | 521 | ## Conditionals 522 | 523 | Conditional bodies should always use braces even when a conditional body could be written without braces (e.g., it is one line only) to prevent errors. These errors include adding a second line and expecting it to be part of the if-statement. Another, [even more dangerous defect](http://programmers.stackexchange.com/a/16530) may happen where the line "inside" the if-statement is commented out, and the next line unwittingly becomes part of the if-statement. In addition, this style is more consistent with all other conditionals, and therefore more easily scannable. 524 | 525 | **Preferred:** 526 | ```objc 527 | if (!error) { 528 | return success; 529 | } 530 | ``` 531 | 532 | **Not Preferred:** 533 | ```objc 534 | if (!error) 535 | return success; 536 | ``` 537 | 538 | or 539 | 540 | ```objc 541 | if (!error) return success; 542 | ``` 543 | 544 | ### Ternary Operator 545 | 546 | The Ternary operator, `?:` , should only be used when it increases clarity or code neatness. A single condition is usually all that should be evaluated. Evaluating multiple conditions is usually more understandable as an `if` statement, or refactored into instance variables. In general, the best use of the ternary operator is during assignment of a variable and deciding which value to use. 547 | 548 | Non-boolean variables should be compared against something, and parentheses are added for improved readability. If the variable being compared is a boolean type, then no parentheses are needed. 549 | 550 | **Preferred:** 551 | ```objc 552 | NSInteger value = 5; 553 | result = (value != 0) ? x : y; 554 | 555 | BOOL isHorizontal = YES; 556 | result = isHorizontal ? x : y; 557 | ``` 558 | 559 | **Not Preferred:** 560 | ```objc 561 | result = a > b ? x = c > d ? c : d : y; 562 | ``` 563 | 564 | ## Init Methods 565 | 566 | Init methods should follow the convention provided by Apple's generated code template. A return type of 'instancetype' should also be used instead of 'id'. 567 | 568 | ```objc 569 | - (instancetype)init { 570 | self = [super init]; 571 | if (self) { 572 | // ... 573 | } 574 | return self; 575 | } 576 | ``` 577 | 578 | See [Class Constructor Methods](#class-constructor-methods) for link to article on instancetype. 579 | 580 | ## Class Constructor Methods 581 | 582 | Where class constructor methods are used, these should always return type of 'instancetype' and never 'id'. This ensures the compiler correctly infers the result type. 583 | 584 | ```objc 585 | @interface Airplane 586 | + (instancetype)airplaneWithType:(RWTAirplaneType)type; 587 | @end 588 | ``` 589 | 590 | More information on instancetype can be found on [NSHipster.com](http://nshipster.com/instancetype/). 591 | 592 | ## CGRect Functions 593 | 594 | When accessing the `x`, `y`, `width`, or `height` of a `CGRect`, always use the [`CGGeometry` functions](http://developer.apple.com/library/ios/#documentation/graphicsimaging/reference/CGGeometry/Reference/reference.html) instead of direct struct member access. From Apple's `CGGeometry` reference: 595 | 596 | > All functions described in this reference that take CGRect data structures as inputs implicitly standardize those rectangles before calculating their results. For this reason, your applications should avoid directly reading and writing the data stored in the CGRect data structure. Instead, use the functions described here to manipulate rectangles and to retrieve their characteristics. 597 | 598 | **Preferred:** 599 | 600 | ```objc 601 | CGRect frame = self.view.frame; 602 | 603 | CGFloat x = CGRectGetMinX(frame); 604 | CGFloat y = CGRectGetMinY(frame); 605 | CGFloat width = CGRectGetWidth(frame); 606 | CGFloat height = CGRectGetHeight(frame); 607 | CGRect frame = CGRectMake(0.0, 0.0, width, height); 608 | ``` 609 | 610 | **Not Preferred:** 611 | 612 | ```objc 613 | CGRect frame = self.view.frame; 614 | 615 | CGFloat x = frame.origin.x; 616 | CGFloat y = frame.origin.y; 617 | CGFloat width = frame.size.width; 618 | CGFloat height = frame.size.height; 619 | CGRect frame = (CGRect){ .origin = CGPointZero, .size = frame.size }; 620 | ``` 621 | 622 | ## Golden Path 623 | 624 | When coding with conditionals, the left hand margin of the code should be the "golden" or "happy" path. That is, don't nest `if` statements. Multiple return statements are OK. 625 | 626 | **Preferred:** 627 | 628 | ```objc 629 | - (void)someMethod { 630 | if (![someOther boolValue]) { 631 | return; 632 | } 633 | 634 | //Do something important 635 | } 636 | ``` 637 | 638 | **Not Preferred:** 639 | 640 | ```objc 641 | - (void)someMethod { 642 | if ([someOther boolValue]) { 643 | //Do something important 644 | } 645 | } 646 | ``` 647 | 648 | ## Error handling 649 | 650 | When methods return an error parameter by reference, switch on the returned value, not the error variable. 651 | 652 | **Preferred:** 653 | ```objc 654 | NSError *error; 655 | if (![self trySomethingWithError:&error]) { 656 | // Handle Error 657 | } 658 | ``` 659 | 660 | **Not Preferred:** 661 | ```objc 662 | NSError *error; 663 | [self trySomethingWithError:&error]; 664 | if (error) { 665 | // Handle Error 666 | } 667 | ``` 668 | 669 | Some of Apple’s APIs write garbage values to the error parameter (if non-NULL) in successful cases, so switching on the error can cause false negatives (and subsequently crash). 670 | 671 | 672 | ## Singletons 673 | 674 | Singleton objects should use a thread-safe pattern for creating their shared instance. 675 | ```objc 676 | + (instancetype)sharedInstance { 677 | static id sharedInstance = nil; 678 | 679 | static dispatch_once_t onceToken; 680 | dispatch_once(&onceToken, ^{ 681 | sharedInstance = [[self alloc] init]; 682 | }); 683 | 684 | return sharedInstance; 685 | } 686 | ``` 687 | This will prevent [possible and sometimes prolific crashes](http://cocoasamurai.blogspot.com/2011/04/singletons-your-doing-them-wrong.html). 688 | 689 | 690 | ## Line Breaks 691 | 692 | Line breaks are an important topic since this style guide is focused for print and online readability. 693 | 694 | For example: 695 | ```objc 696 | self.productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers]; 697 | ``` 698 | A long line of code like this should be carried on to the second line adhering to this style guide's Spacing section (two spaces). 699 | ```objc 700 | self.productsRequest = [[SKProductsRequest alloc] 701 | initWithProductIdentifiers:productIdentifiers]; 702 | ``` 703 | 704 | 705 | ## Smiley Face 706 | 707 | Smiley faces are a very prominent style feature of the raywenderlich.com site! It is very important to have the correct smile signifying the immense amount of happiness and excitement for the coding topic. The end square bracket is used because it represents the largest smile able to be captured using ascii art. A half-hearted smile is represented if an end parenthesis is used, and thus not preferred. 708 | 709 | **Preferred:** 710 | ```objc 711 | :] 712 | ``` 713 | 714 | **Not Preferred:** 715 | ```objc 716 | :) 717 | ``` 718 | 719 | 720 | ## Xcode project 721 | 722 | The physical files should be kept in sync with the Xcode project files in order to avoid file sprawl. Any Xcode groups created should be reflected by folders in the filesystem. Code should be grouped not only by type, but also by feature for greater clarity. 723 | 724 | When possible, always turn on "Treat Warnings as Errors" in the target's Build Settings and enable as many [additional warnings](http://boredzo.org/blog/archives/2009-11-07/warnings) as possible. If you need to ignore a specific warning, use [Clang's pragma feature](http://clang.llvm.org/docs/UsersManual.html#controlling-diagnostics-via-pragmas). 725 | 726 | # Other Objective-C Style Guides 727 | 728 | If ours doesn't fit your tastes, have a look at some other style guides: 729 | 730 | * [Robots & Pencils](https://github.com/RobotsAndPencils/objective-c-style-guide) 731 | * [New York Times](https://github.com/NYTimes/objective-c-style-guide) 732 | * [Google](http://google-styleguide.googlecode.com/svn/trunk/objcguide.xml) 733 | * [GitHub](https://github.com/github/objective-c-conventions) 734 | * [Adium](https://trac.adium.im/wiki/CodingStyle) 735 | * [Sam Soffes](https://gist.github.com/soffes/812796) 736 | * [CocoaDevCentral](http://cocoadevcentral.com/articles/000082.php) 737 | * [Luke Redpath](http://lukeredpath.co.uk/blog/my-objective-c-style-guide.html) 738 | * [Marcus Zarra](http://www.cimgf.com/zds-code-style-guide/) 739 | --------------------------------------------------------------------------------