- Language
- Code Organization
- Spacing
- Comments
- Naming
- Methods
- Variables
- Type Safety
- Property Attributes
- Dot Notation Syntax
- Literals
- Constants
- Enumerated Types
- Case Statements
- Private Properties
- Booleans
- Conditionals
- Init Methods
- Class Constructor Methods
- CGRect Functions
- Golden Path
- Error handling
- Singletons
- Xcode Project
US English should be used for everything including variable and class names, documentation and comments.
Preferred:
UIColor *myColor = [UIColor whiteColor];
Not Preferred:
UIColor *myColour = [UIColor whiteColor];
Use #pragma mark -
to categorize methods in functional groupings and protocol/delegate implementations following this general structure:
#pragma mark - Base class name
- (instancetype)init {}
- (void)viewDidLoad {}
- (void)viewWillAppear:(BOOL)animated {}
- (void)didReceiveMemoryWarning {}
#pragma mark - UITextFieldDelegate
#pragma mark - UITableViewDataSource
#pragma mark - UITableViewDelegate
#pragma mark - Actions
- (IBAction)submitData:(id)sender {}
#pragma mark - Private
- (void)privateMethod {}
#pragma mark - Public
- (void)publicMethod {}
Use #pragma mark
for subcategories (except the first one) this way:
#pragma mark - Private
#pragma mark - First
- (void)firstMethod {}
#pragma mark Second
- (void)secondMethod {}
There should be one newline before and after the #pragma mark
.
The order of import groups separated by blank lines should be this:
- For
.m
files, the counterpart.h
file. - 3rd party frameworks.
- 3rd party libraries.
- Own utility methods.
- Own
UIView
orNSObject
subclasses. - The rest of the imports (interface elements, view controllers) sorted alphabetically or rarely by the order of use.
//
// SettingsViewController.m
//
#import "SettingsViewController.h"
#import <FacebookSDK/FacebookSDK.h>
#import "DateTools.h"
#import "DatabaseUtils.h"
#import "AutoupdatingLabel.h"
#import "DifficultyViewController.h"
#import "ProfileViewController.h"
#import "SocialViewController.h"
- Indent using tabs. Never indent with spaces. 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. - One space should be added before the first opening parenthesis and braces and none between parantheses and their contents.
Preferred:
if (user.isHappy) {
// something
} else {
// something else
}
Not Preferred:
if(user.isHappy)
{
// something
}
else{
// 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.
- Prefer using auto-synthesis. But if necessary,
@synthesize
and@dynamic
should each be declared on new lines in the implementation. - Colon-aligning method invocation should be avoided.
Preferred:
// blocks are easily readable
[UIView animateWithDuration:1.0 animations:^{
// something
} completion:^(BOOL finished) {
// something
}];
Not Preferred:
// colon-aligning makes the block indentation hard to read
[UIView animateWithDuration:1.0
animations:^{
// something
}
completion:^(BOOL finished) {
// something
}];
- There should be one newline after the method's header for improved readability.
Preferred:
- (void)myMethod {
// something
}
Not Preferred:
- (void)myMethod {
// something
}
- Don't put a space between an object type and the protocol it conforms to.
Preferred:
@property (weak, nonatomic) id<MyDelegate> myDelegate;
Not Preferred:
@property (weak, nonatomic) id <MyDelegate> myDelegate;
- Separate class extension and implementation content by newlines.
Preferred:
@interface DatabaseManager ()
// properties
@end
@implementation MyClass
// body (private constants and methods)
@end
- When doing math, use a single space between operators, Unless that operator is unary, in which case don't use a space.
Preferred:
NSInteger index = position % 2 + 25;
index++;
index += 1;
Not Preferred:
NSInteger index = position%2+25;
NSInteger index=position % 2 + 25;
index ++;
index + = 1;
- Generally, the order of statements should be: variable declaration, property accessing and method calling, separated by one newline.
- (void)loadViews {
UILabel *titleLabel = [UILabel alloc] init];
titleLabel.text = @"Settings";
titleLabel.center = self.view.center;
[titleLabel setNeedsLayout];
}
- Always end a file with a newline.
Preferred:
@end
Not Preferred:
@end
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. Exception: This does not apply to those comments used to generate documentation.
Comments regarding one line should be added at the end of it separated by one space and comments regarding multiple lines should be added before the first line. The comment text and //
should be separated by one space.
Preferred:
NSInteger abstractNumber; // comment
// comment
NSInteger oneAbstractNumber;
NSInteger anotherAbstractNumber;
Not Preferred:
NSInteger abstractNumber;// comment
NSInteger abstractNumber; //comment
NSInteger oneAbstractNumber;//comment
NSInteger anotherAbstractNumber;
Apple naming conventions should be adhered to wherever possible.
Long, descriptive method and variable names are good.
Preferred:
UIButton *settingsButton;
UIViewController *mainViewController;
Not Preferred:
UIButton *setBut;
UIViewController *mainVC;
For IBOutlets, the name should start with its class name without the prefix for easier autocompletion of code.
Preferred:
@property (strong, nonatomic) IBOutlet UIButton *buttonSettings;
Not Preferred:
@property (strong, nonatomic) IBOutlet UIButton *settingsButton;
A three letter prefix should always be used for class names and constants, however may be omitted for Core Data entity names.
Avoid using overly simple names like Model
, View
, Object
.
Constants should be camel-case with all words capitalized and prefixed by the related class name for clarity.
Preferred:
static NSTimeInterval const IOTutorialViewControllerNavigationFadeAnimationDuration = 0.3;
Not Preferred:
static NSTimeInterval const fadetime = 1.7;
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.
Preferred:
@property (strong, nonatomic) NSString *descriptiveVariableName;
Not Preferred:
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.
.
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.
Local variables should not contain underscores.
Use descriptive file namings. Describe what the asset is used for, whether it is a background, button or image. Delimit the words by underscore and use only lowercase, following this format:
<module>_<element type>_<descriptive name>_<status>[@<retina>].png
Preferred:
login_background@2x.png
login_button_register_normal@2x.png
login_button_register_highlighted@2x.png
login_button_register_disabled@2x.png
login_button_register_selected@2x.png
login_icon_company.png
settings_cell_label_background_company.png
Not Preferred:
background@2x.png
button_normal@2x.png
login_button_register_normal_2x.png
highlighted_login_button_register@2x.png
disabled_login_button_register@2x.png
selected_login_button_register@2x.png
icon_company_login.png
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.
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;
- (id)taggedView: (NSInteger)tag;
- (id)taggedView:(NSInteger) tag;
- (instancetype)initWithWidth:(CGFloat)width andHeight:(CGFloat)height;
- (instancetype)initWith:(int)width and:(int)height; // never do this.
Avoid having empty methods in classes unless they are overriding a method and it needs to be empty.
Preferred:
- (void)viewDidLoad {
[super viewDidLoad];
// something
}
Not Preferred:
- (void)viewDidLoad {
[super viewDidLoad];
}
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.
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.
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.
Preferred:
@interface IOTutorial : NSObject
@property (strong, nonatomic) NSString *tutorialName;
@end
Not Preferred:
@interface IOTutorial : NSObject {
NSString *tutorialName;
}
Be as type safe as possible. Avoid using id
or base classes like NSObject
or UIView
where possible. Use the lowest common multiple preferring a protocol or an abstract class.
Preferred:
+ (StorageManager *)managerWithData:(StorageData *)data {
return [[StorageManager alloc] initWithData:data];
}
Not Preferred:
+ (id)managerWithData:(id)data {
return [[StorageManager alloc] initWithData:(StorageData *)data];
}
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.
Preferred:
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (strong, nonatomic) NSString *tutorialName;
Not Preferred:
@property (nonatomic, weak) IBOutlet UIView *containerView;
@property (nonatomic) NSString *tutorialName;
Properties with mutable counterparts (e.g. NSString) should prefer copy
instead of strong
.
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.
Preferred:
@property (copy, nonatomic) NSString *tutorialName;
Not Preferred:
@property (strong, nonatomic) NSString *tutorialName;
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.
Dot notation should always be used for accessing and mutating properties, as it makes code more concise. The only eception are the cases where the corresponding accesor method has been overriden, in which case the bracket notation should be used to avoid confusion. Bracket notation is preferred in all other instances.
Preferred:
NSInteger arrayCount = self.array.count;
view.backgroundColor = [UIColor orangeColor];
[UIApplication sharedApplication].delegate;
Not Preferred:
NSInteger arrayCount = [self.array count];
[view setBackgroundColor:[UIColor orangeColor]];
UIApplication.sharedApplication.delegate;
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.
Because literal strings are created using @
and the string eclosed in quotes, with no space, all other literals should be created in the same way too keep them consistent.
Preferred:
NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"];
NSDictionary *productManagers = @{@"iPhone": @"Kate", @"iPad": @"Kamal", @"Mobile Web": @"Bill"};
NSNumber *shouldUseLiterals = @(YES);
NSNumber *buildingStreetNumber = @(10018);
Not Preferred:
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 *buildingStreetNumber = [NSNumber numberWithInteger:10018];
or
NSArray *names = @[ @"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul" ];
NSDictionary *productManagers = @{ @"iPhone": @"Kate", @"iPad": @"Kamal", @"Mobile Web": @"Bill" };
NSNumber *shouldUseLiterals = @YES;
NSNumber *buildingStreetNumber = @10018;
NSNumber *postalCodeNumber = @( 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.
Preferred:
static NSString *const IOAboutViewControllerCompanyName = @"iulianonofrei.com";
static CGFloat const IOImageThumbnailHeight = 50.0;
Not Preferred:
#define CompanyName @"iulianonofrei.com"
#define thumbnailHeight 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 the macro NS_ENUM()
to facilitate and encourage use of fixed underlying types.
typedef NS_ENUM(NSInteger, IOLeftMenuTopItemType) {
IOLeftMenuTopItemMain,
IOLeftMenuTopItemShows,
IOLeftMenuTopItemSchedule
};
You can also make explicit value assignments (showing older k-style constant definition):
typedef NS_ENUM(NSInteger, IOGlobalConstants) {
IOPinSizeMin = 1,
IOPinSizeMax = 5,
IOPinCountMin = 100,
IOPinCountMax = 500,
};
Older k-style constant definitions should be avoided.
Not Preferred:
enum GlobalConstants {
kMaxPinSize = 5,
kMaxPinCount = 500,
};
Braces are not required for case statements, unless enforced by the complier.
When a case contains more than one line, braces should be added. In this case, all other case
s should contain braces too keep the switch
consistent.
The line containing the break
statement should be separated by one newline from the rest of the case
s body.
switch (condition) {
case 1: {
// ...
break;
}
case 2: {
// ...
// multi-line example using braces
break;
}
case 3: {
// ...
break;
}
default: {
// ...
break;
}
}
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.
switch (condition) {
case 1:
// fall-through
case 2:
// code executed for values 1 and 2
break;
default:
// ...
break;
}
When using an enumerated type for a switch, 'default' is not needed. For example:
IOLeftMenuTopItemType menuType = IOLeftMenuTopItemMain;
switch (menuType) {
case IOLeftMenuTopItemMain:
// ...
break;
case IOLeftMenuTopItemShows:
// ...
break;
case IOLeftMenuTopItemSchedule:
// ...
break;
}
Private properties should be declared in class extensions (anonymous categories) in the implementation file of a class. Named categories (such as IOPrivate
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.
@interface IODetailViewController ()
@property (strong, nonatomic) IBOutlet;
@property (strong, nonatomic) GADBannerView *googleAdView;
@property (strong, nonatomic) ADBannerView *iAdView;
@property (strong, nonatomic) UIWebView *adXWebView;
@end
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.
This allows for more consistency across files and greater visual clarity.
Preferred:
if (someObject) {}
if (![anotherObject boolValue]) {}
Not Preferred:
if (someObject == nil) {}
if ([anotherObject boolValue] == NO) {}
if (isAwesome == YES) {} // never do this.
if (isAwesome == true) {} // never do this.
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:
@property (assign, getter=isEditable) BOOL editable;
Text and example taken from the Cocoa Naming Guidelines.
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.
Preferred:
if (!error) {
return success;
}
Not Preferred:
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. In general, the best use of the ternary operator is during assignment of a variable and deciding which value to use.
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.
Preferred:
NSInteger value = 5;
result = (value != 0) ? x : y;
BOOL isHorizontal = YES;
result = isHorizontal ? x : y;
Not Preferred:
result = a > b ? x = c > d ? c : d : y;
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'.
- (instancetype)init {
self = [super init];
if (self) {
// ...
}
return self;
}
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.
@interface Airplane
+ (instancetype)airplaneWithType:(IOAirplaneType)type;
@end
More information on instancetype can be found on NSHipster.com.
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.
Preferred:
CGRect frame = self.view.frame;
CGFloat x = CGRectGetMinX(frame);
CGFloat y = CGRectGetMinY(frame);
CGFloat width = CGRectGetWidth(frame);
CGFloat height = CGRectGetHeight(frame);
CGRect frame = CGRectMake(0.0, 0.0, width, height);
Not Preferred:
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;
CGRect frame = (CGRect){ .origin = CGPointZero, .size = frame.size };
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.
Preferred:
- (void)someMethod {
if (![someOther boolValue]) {
return;
}
// something important
}
Not Preferred:
- (void)someMethod {
if ([someOther boolValue]) {
// something important
}
}
When methods return an error parameter by reference, switch on the returned value, not the error variable.
Preferred:
NSError *error;
if (![self trySomethingWithError:&error]) {
// handle error
}
Not Preferred:
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).
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 new];
});
return sharedInstance;
}
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.
Inspired from these sources: