This style guide outlines the coding conventions of our iOS team.
- Dot-Notation Syntax
- Spacing
- Conditionals
- Error handling
- Methods
- Variables
- Naming
- Comments
- Init & Dealloc
- Literals
- Constants
- Enumerated Types
- Private Properties
- Image Naming
- Booleans
- Singletons
- Xcode Project
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;
- 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 new line and close on a new line. - Bracket opens and closes below each other.
For example:
if (user.isHappy)
{
if (user.hasCar)
{
[self organizeParty];
}
[self doSomething];
}
else
{
[self doSomethingElse];
}
@synthesize
and@dynamic
should each be declared on new lines in the implementation.
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 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.
For example:
if (error == nil)
{
return success;
}
Not:
if (!error)
return success;
or
if (!error) return success;
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.
For example:
result = a > b ? x : y;
Not:
result = a > b ? x = c > d ? c : d : y;
When methods return an error parameter by reference, switch on the returned value, not the error variable.
For example:
NSError *error = nil;
if ([self trySomethingWithError:&error] == NO)
{
// 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).
In method signatures, there should be a space after the scope (-/+ symbol). There should be a space between the method segments.
For Example:
- (void)setExampleText:(NSString *)text image:(UIImage *)image;
Variables should be named as descriptively as possible. Single letter variable names should be avoided except in for()
loops.
Asterisks indicating pointers belong with the variable, e.g., NSString *text
not NSString* text
or NSString * text
, except in the case of constants.
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 on using Accessor Methods in Initializer Methods and dealloc, see here.
For example:
@interface NYTSection: NSObject
@property (nonatomic, retaine) NSString *headline;
@property (nonatomic, assign) NSInteger objectCount;
@end
Not:
@interface NYTSection : NSObject
{
NSString *headline;
}
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
ot RLS
) should always be used for class names, however may be omitted for Core Data entity names.
For example:
@interface RLSLoginViewController : UIViewController
{
}
Not:
@interface LoginViewController : UIViewController
{
}
Properties should be camel-case with the leading word being lowercase. Does not use @synthesize if it is not needed. Otherwise, in order to be consistent, the backing instance variables for these properties should be camel-case with the leading word being lowercase and a leading underscore. This is the same format as Xcode's default synthesis.
For example:
@synthesize descriptiveVariableName = _descriptiveVariableName;
Not:
id varnm;
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.
. Local variables should not contain underscores.
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.
dealloc
methods should be placed at the top of the implementation, directly after the @synthesize
and @dynamic
statements. init
should be placed directly below the dealloc
methods of any class.
init
methods should be structured like this:
- (instancetype)init
{
self = [super init]; // or call the designated initalizer
if (self)
{
// Custom initialization
}
return self;
}
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];
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.
For example:
static NSString * const CompanyName = @"The New York Times Company";
static const CGFloat ThumbnailHeight = 50.0;
Not:
#define NYTAboutViewControllerCompanyName @"The New York Times Company"
#define NYTImageThumbnailHeight 2
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()
Example:
typedef NS_ENUM(NSInteger, NYTAdRequestState)
{
NYTAdRequestStateInactive,
NYTAdRequestStateLoading
};
Private properties should be declared in class extensions (anonymous categories) in the implementation file of a class. Named categories (such as NYTPrivate
or private
) should never be used unless extending another class.
For example:
@interface NYTAdvertisement ()
@property (nonatomic, strong) GADBannerView *googleAdView;
@property (nonatomic, strong) ADBannerView *iAdView;
@property (nonatomic, strong) UIWebView *adXWebView;
@end
Not:
@interface NYTAdvertisement (Private)
@property (nonatomic, strong) GADBannerView *googleAdView;
@property (nonatomic, strong) ADBannerView *iAdView;
@property (nonatomic, strong) UIWebView *adXWebView;
@end
Image names should be named consistently to preserve organization and developer sanity. They should be named as one camel case string with a description of their purpose, followed by the un-prefixed name of the class or property they are customizing (if there is one), followed by a further description of color and/or placement, and finally their state.
For example:
RefreshBarButtonItem
/RefreshBarButtonItem@2x
andRefreshBarButtonItemSelected
/RefreshBarButtonItemSelected@2x
ArticleNavigationBarWhite
/ArticleNavigationBarWhite@2x
andArticleNavigationBarBlackSelected
/ArticleNavigationBarBlackSelected@2x
.
Images that are used for a similar purpose should be grouped in respective groups in an Images folder.
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.
This allows for more consistency across files and greater visual clarity.
For example:
if (someObject == nil)
{
}
if (someObject)
{
}
if (someObject != nil)
{
}
Not:
if (!someObject) {
}
For a BOOL
, here are two examples:
if (isAwesome)
if (someObject.boolValue == NO)
Not:
if (![someObject boolValue])
if (isAwesome == YES) // Never do this.
Singleton objects should use a thread-safe pattern for creating their shared instance. Use "SynthesizeSingleton.h" to generate a singleton. Example .h file:
#import <Foundation/Foundation.h>
@interface Internet : NSObject
+ (Internet *)sharedInstance;
@end
Example .m file:
#import "Internet.h"
#import "SynthesizeSingleton.h"
@implementation Internet
SYNTHESIZE_SINGLETON_FOR_CLASS(Internet)
@end
This will prevent possible and sometimes prolific crashes.
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.
When possible, always turn on "Treat Warnings as Errors" in the target's Build Settings and enable as many additional warnings as possible. If you need to ignore a specific warning, use Clang's pragma feature.
Use git ignore file if you use git as SCM system.
If ours doesn't fit your tastes, have a look at some other style guides: