This style guide outlines the coding conventions of the iOS team at Wedding Party. We welcome your feedback in issues, and tweets. Also, we're hiring.
Thanks to The New York Times for sharing their style guide.
- Dot-Notation Syntax
- Spacing
- Conditionals
- Error handling
- Methods
- Variables
- Naming
- Comments
- Init & Dealloc
- Literals
- CGRect Functions
- Constants
- Private Properties
- Image Naming
- Singletons
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 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 separate functionality, but often there should probably be new methods.
@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) {
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;
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).
In method signatures, there should be exactly one space after the scope (-/+ symbol). There should be a space between the method segments. And there should be no spaces between the parameter type and the parameter name.
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.
For example:
@interface NYTSection: NSObject
@property (nonatomic) NSString *headline;
@end
Not:
@interface NYTSection : NSObject {
NSString *headline;
}
Direct instance variable access should be avoided except in initializer methods (init
, initWithCoder:
, etc…), dealloc
methods and within custom setters and getters. Inside init
methods, do not use self
unless necessary. For more information on using Accessor Methods in Initializer Methods and dealloc, see here.
For example:
@interface NYTSection: NSObject
- (id)initWithFrame:(CGRect)frame
{
id = [self init];
if (self) {
_varName = @"Some initial value";
}
return self;
}
@end
Apple naming conventions should be adhered to wherever possible, especially those related to memory management rules (NARC).
All private methods should begin with GT_
. Apple reserves all names begining with a single underscore for it's own use.
For example:
- (void)GT_configTableView
Not
- (void)_configTableView
All constants should begin with C_
followed by Camel case.
For example:
static const NSString C_SyncState = @"C_SyncState";
Not:
static const NSString kSyncState = @"C_SyncState";
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.
Using self.
is the same as calling a setter or getter. So REMEMBER, you should never use self.
inside a custom setter or getter implementation.
Always use _
notation to access an ivar in init methods, setters & getters.
For example:
- (NSString *)getName {
_name = _firstName;
}
Not:
- (NSString *)getName {
self.name = _firstName;
}
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.
init
should be placed at the top of the class.
view
lifecycle methods should be placed after the init
methods.
Public methods should be placed just after the view
lifecycle methods, followed by private methods (GT_
).
Delegate methods should be placed after the private methods.
dealloc
methods should be placed at the bottom of the implementation.
#pragma mark -
should be used to delinate all groups of methods, especially Actions, Delegate methods for any protocol.
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];
When accessing the x
, y
, width
, or height
of a CGRect
, always use the CGGeometry
functions instead of direct struct member access. From Apple's CGGeometry
reference:
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.
For example:
CGRect frame = self.view.frame;
CGFloat x = CGRectGetMinX(frame);
CGFloat y = CGRectGetMinY(frame);
CGFloat width = CGRectGetWidth(frame);
CGFloat height = CGRectGetHeight(frame);
Not:
CGRect frame = self.view.frame;
CGFloat x = frame.origin.x;
CGFloat y = frame.origin.y;
CGFloat width = frame.size.width;
CGFloat height = frame.size.height;
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 C_AboutViewControllerCompanyName = @"Wedding Party";
static const CGFloat C_ImageThumbnailHeight = 50.0;
Not:
#define CompanyName @"Wedding Party"
#define thumbnailHeight 2
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
All image names should begin with a 2 letter abbreviation to signify where the images are used in the app. eg. FT_ is used by all images in the First Timer screens.
For example:
FT_close_button@2x.png
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 alloc] init];
});
return sharedInstance;
}
This will prevent possible and sometimes prolific crashes.
The code should should be committed without warnings. That way, when new warnings appear for some reason, it is easier to detect and fix it.
Items for further discussion:
- Moving away from using Nibs. Not using Storyboards.
- Core Data changes should always happen on master branch.
- Commiting code with build warnings.