1. Dot Syntax

Dot notation should always be used for accessing and mutating properties. Bracket notation is preferred in all other instances.

For example:

 view.backgroundColor = [UIColor orangeColor];  
 [UIApplication sharedApplication].delegate;  

Not:

 [view setBackgroundColor:[UIColor orangeColor]];  
 UIApplication.sharedApplication.delegate;  
    1. Spacing

      Indent using 4 spaces. Never indent with tabs. Be sure to set this preference in Xcode.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.

For example:

 if (user.isHappy) {  
   // Do something   
 }  
 else {  
   // Do something else   
 }  

There should be exactly one blank line between methods to aid in visual clarity and organization.

Whitespace within methods should be used to separate functionality (though often this can indicate an opportunity to split the method into several, smaller methods). In methods with long or verbose names, a single line of whitespace may be used to provide visual separation before the method’s body.

@synthesize and @dynamic should each be declared on new lines in the implementation.

    1. Control Structures

There should always be a space after the control structure (i.e. if, else, etc).

If/Else

 if (button.enabled) {  
   // Stuff  
 } else if (otherButton.enabled) {  
   // Other stuff  
 } else {  
   // More stuf  
 }  

else statements should begin on the same line as their preceding if statement.

 // Comment explaining the conditional  
 if (something) {  
   // Do stuff  
 }  
 // Comment explaining the alternative  
 else {  
   // Do other stuff  
 }  

If comments are desired around the if and else statement, they should be formatted like the example above.

Switch

 switch (something.state) {  
   case 0: {  
     // Something  
     break;  
   }  
   case 1: {  
     // Something  
     break;  
   }  
   case 2:  
   case 3: {  
     // Something  
     break;  
   }  
   default: {  
     // Something  
     break;  
   }  
 }  

Brackets are desired around each case. If multiple cases are used, they should be on separate lines. default should always be the last case and should always be included.

For

 for (NSInteger i = 0; i < 10; i++) {  
   // Do something  
 }  
 for (NSString *key in dictionary) {  
   // Do something  
 }  

When iterating using integers, it is preferred to start at 0 and use < rather than starting at 1 and using <=. Fast enumeration is generally preferred.

While

 while (something < somethingElse) {  
   // Do something  
 }  

    1. Ternary Operator

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 named variables.

For example:

 result = a > b ? x : y;  

Not:

 result = a > b ? x = c > d ? c : d : y;  
    1. Error Handling

When methods return an error parameter by reference, switch on the returned value, not the error variable.

For example:

 NSError *error;   
 if (![self trySomethingWithError:&error]) {     
   // Handle Error  
 }  

Not:

 NSError *error;   
 [self trySomethingWithError:&error];  
 if (error) {     
   // Handle Error   
 }  

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).

    1. Methods

There should always be a space between the – or + and the return type ((void) in this example). There should never be a space between the return type and the method name.

There should never be a space before or after colons. If the parameter type is a pointer, there should always be a space between the class and the *.

There should always be a space between the end of the method and the opening bracket. The opening bracket should never be on the following line.

There should always be two new lines between methods. This matches some Xcode templates (although they change a lot) and increase readability.

The usage of the word “and” is reserved. It should not be used for multiple parameters as illustrated in the initWithWidth: height: example below.

Preferred:

 - (void)setExampleText:(NSString *)text image:(UIImage *)image;  
 - (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;  
 - (id)viewWithTag:(NSInteger)tag;  
 - (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height;       

Not Preferred:

 -(void)setT:(NSString *)text i:(UIImage *)image;  
 - (void)sendAction:(SEL)aSelector :(id)anObject :(BOOL)flag;  
 - (id)taggedView:(NSInteger)tag;  
 - (instancetype)initWithWidth:(CGFloat)width andHeight:(CGFloat)height;  
 - (instancetype)initWith:(int)width and:(int)height; // Never do this.  
    1. Variables

Variables should be named descriptively, with the variable’s name clearly communicating what the variable is and pertinent information a programmer needs to use that value properly.

For example:

      • NSString *title: It is reasonable to assume a “title” is a string.
      • NSString *titleHTML: This indicates a title that may contain HTML, which needs parsing for display. “HTML” is needed for a programmer to use this variable effectively.
      • NSAttributedString *titleAttributedString: A title, already formatted for display. AttributedString hints that this value is not just a vanilla title, and adding it could be a reasonable choice depending on context.
      • NSDate *now: No further clarification is needed.
      • NSDate *lastModifiedDate: Simply lastModified can be ambiguous; depending on context, one could reasonably assume it is one of a few different types.
      • NSURL *URL vs. NSString *URLString: In situations when a value can reasonably be represented by different classes, it is often useful to disambiguate in the variable’s name.
      • NSString *releaseDateString: Another example where a value could be represented by another class, and the name can help disambiguate.

Single letter variable names should be avoided except as simple counter variables in loops.

Asterisks indicating a type is a pointer should be “attached to” the variable name.

For example,

NSString *text not NSString* text or NSString * text, except in the case of constants (NSString * const NYTConstantString).

Property definitions should be used in place of naked instance variables whenever possible. Direct instance variable access should be avoided except in initializer methods (init, initWithCoder:, etc…), dealloc methods and within custom setters and getters. For more information, see Apple’s docs on using accessor methods in initializer methods and dealloc.

For example:

 @interface NYTSection: NSObject   
 @property (nonatomic) NSString *headline;   
 @end  

Not:

 @interface NYTSection : NSObject {     
   NSString *headline;   
 }  

Variable Qualifiers

When it comes to the variable qualifiers introduced with ARC, the qualifier (__strong, __weak,__unsafe_unretained, __autoreleasing) should be placed between the asterisks and the variable name, e.g., NSString * __weak text.

    1. Naming

Apple naming conventions should be adhered to wherever possible, especially those related to memory management rules (NARC).

Long, descriptive method and variable names are good

For example:

 UIButton *settingsButton;  

Not

 UIButton *setBut;  

A three letter prefix (e.g., NYT) should always be used for class names and constants, however may be omitted for Core Data entity names. Constants should be camel-case with all words capitalized and prefixed by the related class name for clarity. A two letter prefix (e.g., NS) is reserved for use by Apple. 

For example:

 static const NSTimeInterval NYTArticleViewControllerNavigationFadeAnimationDuration = 0.3;  

Not:

 static const NSTimeInterval fadetime = 1.7;  

Properties and local variables should be camel-case with the leading word being lowercase.

Instance variables should be camel-case with the leading word being lowercase, and should be prefixed with an underscore. This is consistent with instance variables synthesized automatically by LLVM. If LLVM can synthesize the variable automatically, then let it.

For example:

 @synthesize descriptiveVariableName = _descriptiveVariableName;  

 

    1. Constants

Constants should be declared as static constants and not #defines unless explicitly being used as a macro.

For example:

 static NSString * const NYTAboutViewControllerCompanyName = @"The New York Times Company";  
 static const CGFloat NYTImageThumbnailHeight = 50.0;  
 #define CompanyName @"The New York Times Company"  
 #define thumbnailHeight 2   

 

    1. Categories

Categories may be used to concisely segment functionality and should be named to describe that functionality.

For example:

 @interface UIViewController (NYTMediaPlaying)   
 @interface NSString (NSStringEncodingDetection)  

Methods and properties added in categories should be named with an app- or organization-specific prefix. This avoids unintentionally overriding an existing method, and it reduces the chance of two categories from different libraries adding a method of the same name. (The Objective-C runtime doesn’t specify which method will be called in the latter case, which can lead to unintended effects.)

For example:

 @interface NSArray (NYTAccessors)  
 - (id)nyt_objectOrNilAtIndex:(NSUInteger)index;  
 @end  

 

    1. Comments

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.

Block comments should generally be avoided, as code should be as self-documenting as possible, with only the need for intermittent, few-line explanations. This does not apply to those comments used to generate documentation.

<<<<<Add pragma mark example with description>>>>


    1. Literals

NSString, NSDictionary, NSArray, and NSNumber literals should be used whenever creating immutable instances of those objects. Pay special care that nil values not be passed into NSArray and NSDictionary literals, as this will cause a crash.

For example:

 NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"];   
 NSDictionary *productManagers = @{@"iPhone": @"Kate", @"iPad": @"Kamal", @"Mobile Web" : @"Bill"};   
 NSNumber *shouldUseLiterals = @YES;   
 NSNumber *buildingZIPCode = @10018;  

Not:

 NSArray *names = [NSArray arrayWithObjects:@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul", nil];   
 NSDictionary *productManagers = [NSDictionary dictionaryWithObjectsAndKeys: @"Kate", @"iPhone", @"Kamal", @"iPad", @"Bill", @"Mobile Web", nil];   
 NSNumber *shouldUseLiterals = [NSNumber numberWithBool:YES];   
 NSNumber *buildingZIPCode = [NSNumber numberWithInteger:10018];  


    1. Enumerated Types

When using enums, use the new fixed underlying type specification, which provides stronger type checking and code completion. The SDK includes a macro to facilitate and encourage use of fixed underlying types: NS_ENUM().

For Example:

 typedef NS_ENUM(NSInteger, RWTLeftMenuTopItemType) {  
  RWTLeftMenuTopItemMain,  
  RWTLeftMenuTopItemShows,  
  RWTLeftMenuTopItemSchedule  
 };  

You can also make explicit value assignments (showing older k-style constant definition):

 typedef NS_ENUM(NSInteger, RWTGlobalConstants) {  
  RWTPinSizeMin = 1,  
  RWTPinSizeMax = 5,  
  RWTPinCountMin = 100,  
  RWTPinCountMax = 500,  
 };  

 

    1. Private Properties

Private properties should be declared in class extensions (anonymous categories) in the implementation file of a class( .m file).

For example:

 @interface NYTAdvertisement ()   
 @property (nonatomic, strong) GADBannerView *googleAdView;   
 @property (nonatomic, strong) ADBannerView *iAdView;   
 @property (nonatomic, strong) UIWebView *adXWebView;   
 @end  
    1. Booleans

Never compare something directly to YES, because YES is defined as 1.

For an object pointer:

 if (!someObject) { } if (someObject == nil) { }  

 

For a BOOL value:

 if (isAwesome) if (!someNumber.boolValue) if (someNumber.boolValue == NO  

Not:

 if (isAwesome == YES) // Never do this  

If the name of a BOOL property is expressed as an adjective, the property’s name can omit the isprefix but should specify the conventional name for the getter.

 For example:

 @property (assign, getter=isEditable) BOOL editable;  

Text and example taken from the Cocoa Naming Guidelines.


    1. Singletons

Singleton objects should use a thread-safe pattern for creating their shared instance.

 + (instancetype)sharedInstance {    
   static id sharedInstance = nil;  
   static dispatch_once_t onceToken;  
   dispatch_once(&onceToken, ^{  
     sharedInstance = [[[self class] alloc] init];    
   });  
    return sharedInstance;   
 }  

This will prevent possible and sometimes frequent crashes.

 

    1. Blocks

Blocks should have a space between their return type and name.

      • Block definitions should omit their return type when possible.
      • Block definitions should omit their arguments if they are void.
      • Parameters in block types should be named unless the block is initialized immediately.
 void (^blockName1)(void) = ^{  
   // do some things  
 };  
 id (^blockName2)(id) = ^ id (id args) {  
   // do some things  
 };  

 

Credit and attribution:
Objective-c-style-guide” by NYTimes