Skip to content

Instantly share code, notes, and snippets.

@endocrimes
Last active Aug 29, 2015
Embed
What would you like to do?
Objective-C style guide

My Objective-C Style guide

This style guide outlines the coding conventions that I try to stick to when writing Objective-C. I'm posting it here mostly as a brain dump and easy reference for the future, and to formalise it a little more.

It's pretty similar to that of the NYTimes. This document is mostly a customised version of that, you should go check theirs out!

Useful Resources

If you're looking to see some of the reasons behind some choices, or for something I haven't covered, look at the sites below, Apples documentation is pretty great.

Table of Contents

Dot-Notation 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;

Categories

Method names in categories should only be prefixed if they are implementation specific. In all other cases, the implementation of a method should not be of importance.

For example:

id object = [array firstObject]; 

Should work regardless of its implementation detail.

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

Conditionals

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. It's also more easy to quickly scan (as it keeps the style of other conditionals).

For example:

if (!error) 
{
    return success;
}

Not:

if (!error)
    return success;

or

if (!error) return success;

Ternary Operator

The Ternary operator, ? , should only be used when it increases clarity or code neatness. A single condition is all that should be evaluated. Multiple conditions should always use if statements.

For example:

result = a > b ? x : y;

Not:

result = a > b ? x = c > d ? c : d : y;

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

Methods

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;

Not:

-(void)setExampleText:(NSString *)text image:(UIImage *)image;

Or:

- (void) setExampleText:(NSString *)text image:(UIImage *)image;

Variables

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, whereby NSString * kConstantName should be used.

Property definitions should be used in place of naked instance variables whenever possible. Direct instance variable access should be avoided except in initialiser methods (init, initWithCoder:, etc…), dealloc methods and within custom setters and getters. For more information on using Accessor Methods in Initialiser Methods and dealloc, see here.

For example:

@interface HNCPost: NSObject

@property (nonatomic) NSString *title;

@end

Not:

@interface HNCPost : NSObject {
    NSString *title;
}

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. DLT) 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 capitalised and prefixed by the related class name for clarity.

For example:

static const NSString * HNCBasePathForAPI = @"http://apiurl.com/api/v1/";

Not:

static const NSString * basePath = @"http://apiurl.com/api/v1/";

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 synthesised automatically by LLVM. If LLVM can synthesise the variable automatically, then let it.

For example:

@synthesize descriptiveVariableName = _descriptiveVariableName;

Not:

id varnm;

Comments

When they are needed, comments should be used to explain why a particular piece of code does something.

Block comments should generally be avoided, as code should be as self-documenting as possible, with only the need for intermittent, few-line explanations.

init and dealloc

init should be placed at the top of an implementation. dealloc methods should be placed at the bottom of the implementation directly above the @end

init methods should be structured like this:

- (instancetype)init 
{
    self = [super init]; 
    if (self) {
        // Custom initialisation
    }

    return self;
}

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 = @[@"Daniel", @"Ross", @"Will", @"Marco"];
NSDictionary *ages = @{@"Daniel" : @17, @"Ross" : @15, @"Will" : @16};
NSNumber *yearOfBirth = @1996;

Constants

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 #defines unless explicitly being used as a macro.

For example:

static NSString * const HNCBasePathForAPI = @"http://path/to/api";

static const CGFloat HNCImagePreviewHeight = 50.0;

Not:

#define APIBasePath @"http://path/to/api"

#define previewHeight 50

Enumerated Types

When using enums, 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, HNCPostType) {
    HNCPostTypeLinkedPage,
    HNCPostTypeWrittenComment
};

Private Properties

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

For example:

@interface DLTAdView ()

@property (nonatomic, strong) GADBannerView *googleAdView;
@property (nonatomic, strong) ADBannerView *iAdView;
@property (nonatomic, strong) UIWebView *adXWebView;

@end

Image Naming

Image names should be named consistently to preserve organisation 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 customising (if there is one), followed by a further description of color and/or placement, and finally their state. Xcode Assets should be used wherever possible.

For example:

  • RefreshBarButtonItem / RefreshBarButtonItem@2x and RefreshBarButtonItemSelected / RefreshBarButtonItemSelected@2x
  • ArticleNavigationBarWhite / ArticleNavigationBarWhite@2x and ArticleNavigationBarBlackSelected / ArticleNavigationBarBlackSelected@2x.

Booleans

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) 
{
// Code
}

Not:

if (someObject == nil) 
{
// Code
}

For a BOOL, here are two examples:

if (isAwesome)
if (![someObject boolValue])

Not:

if ([someObject boolValue] == NO)
if (isAwesome == YES) // 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.

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 alloc] init];
   });

   return sharedInstance;
}

This will prevent possible and sometimes prolific crashes.

Xcode project

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, this is because it's much easier to then navigate outside of Xcode.

Other Objective-C Style Guides

If mine doesn't fit your tastes, have a look at some other style guides:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment