Fork me on GitHub

Alex Rupérez

Objective-C Style Guide

This style guide outlines the coding conventions of the iOS team at Gigigo Mobile Services. We welcome your feedback in issues, pull requests and tweets.

Thanks to all of our contributors.

Introduction

Here are some of the documents from Apple that informed the style guide. If something isn't mentioned here, it's probably covered in great detail in one of these:

Table of Contents

Variable initialization

Always give a value. Declare and initialize them just before use.

For example:

NSInteger i = 0;
NSError *error = nil;

Not:

NSInteger i;
NSError *error;
NSError* error;
NSError *cool_error;

Whitespace

Consistant horizontal and vertical spaces. Use vertical whitespace to divide logic pieces. Whitespace matters.

For example:

CGFloat x = 0.0f;
CGFloat y = 0.0f;

x += 20.0f;
y = x + 20.0f;
x = y + 30.0f;

return (x + y);

Not:

CGFloat x = 0.0f;

CGFloat y = 0.0f;
x += 20.0f;
y = x+20.0f;

x = y+30.0f;
return x+y;

Dot-Notation Syntax

Dot-notation should always be used for accessing and mutating properties. Bracket notation is preferred in all other instances. Use the underscore ivar only on init and dealloc methods.

For example:

self.text = @"text";
NSString *text = self.text;
view.backgroundColor = [UIColor orangeColor];
[UIApplication sharedApplication].delegate;

Not:

_text = @"text";
[self setText:@"text"];
[view setBackgroundColor:[UIColor orangeColor]];
UIApplication.sharedApplication.delegate;

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 and close on a new line.

For example:

if (self)
{
    return;
}
else
{
    return;
}

Not:

if(self) {
    return;
} else {
    return;
}

if (self) return;
else return;

if (self)
    return;
else
    return;
  • 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.

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

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

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 = nil;
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
{

}

- (void)method
{

}

- (void)methodWithParameter:(NSString *)parameter
{

}

Not:

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

}

-(void)method {

}
- (void) methodWithParameter: (NSString*) parameter
{

}

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.

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 GIGSection: NSObject

@property (nonatomic) NSString *headline;
@property (assign, nonatomic, readwrite) NSInteger count;
@property (assign, nonatomic, readwrite) NSInteger totalCount;

@end

Not:

@interface GIGSection : NSObject
{
    NSString *headline;
    NSInteger total_count;
}

@property (assign, nonatomic) NSInteger _count;

@end

Variable Qualifiers

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

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

For example:

static const NSTimeInterval GIGArticleViewControllerNavigationFadeAnimationDuration = 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;

Not:

id varnm;

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.

init and dealloc

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;
}

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;

NSString *string = array[0];
NSString *string = dictionary[@"key"];
mutableArray[0] = self;
mutableDictionary[@"key"] = @"value";

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];

NSString *string = [array objectAtIndex:0];
NSString *string = [dictionary objectForKey:@"key"];
[mutableArray replaceObjectAtIndex:0 withObject:self];
[mutableDictionary setObject:@"value" forKey:@"key"];

CGRect Functions

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

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. Global or public constants should have the 3 characters prefix.

For example:

static NSString * const kGIGAboutViewControllerCompanyName = @"Gigigo Mobile Services";

static CGFloat const kGIGImageThumbnailHeight = 50.0f;

static CGPoint const kGIGDefaultPoint = { 0.0f, 0.0f };

Not:

#define CompanyName @"Gigigo Mobile Services"

#define thumbnailHeight 2

#define defaultPoint CGPointMake(0.0f,0.0f)

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, GIGAdRequestState) {
    GIGAdRequestStateInactive,
    GIGAdRequestStateLoading
};

Bitmasks

When working with bitmasks, use the NS_OPTIONS macro.

Example:

typedef NS_OPTIONS(NSUInteger, GIGAdCategory) {
  GIGAdCategoryAutos      = 1 << 0,
  GIGAdCategoryJobs       = 1 << 1,
  GIGAdCategoryRealState  = 1 << 2,
  GIGAdCategoryTechnology = 1 << 3
};

Blocks

For example:

[UIView animateWithDuration:1.0f animations:^{

} completion:^(BOOL finished) {

}];

typedef void(^GIGLoadingCompletion)(BOOL success, id result, NSError *error);

- (void)performWithCompletion:(GIGLoadingCompletion)completion
{

}

Not:

[UIView animateWithDuration:1.0f
		 animations:^{
	 
		 }
		 completion:^(BOOL finished) {

}];

- (void)performWithInlineCompletion:(void(^)(BOOL success, id result, NSError *error))completion
{

}

Private Properties

Private properties should be declared in class extensions (anonymous categories) in the implementation file of a class. Named categories (such as GIGPrivate or private) should never be used unless extending another class.

For example:

@interface GIGAdvertisement ()

@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 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 and RefreshBarButtonItemSelected / RefreshBarButtonItemSelected@2x
  • ArticleNavigationBarWhite / ArticleNavigationBarWhite@2x and ArticleNavigationBarBlackSelected / ArticleNavigationBarBlackSelected@2x.

Images that are used for a similar purpose should be grouped in respective groups in an Images folder.

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

Not:

if (someObject == nil) {
	
}

For a BOOL, here are two examples:

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

Not:

if (isAwesome == YES) // Never do this.
if ([someObject boolValue] == NO)

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.

ViewController

@interface GIGViewController ()

@property (weak, nonatomic) IBOutlet UIButton *buttonWhatever;

@end

@implementation GIGViewController

#pragma mark - Init and Dealloc

- (void)dealloc
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changedWhatever:) name:@"GIGWhateverNotification" object:nil];
}

#pragma mark - Custom Accessors

#pragma mark - IBActions

- (IBAction)tapButtonWhatever
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

#pragma mark - Notifications

- (void)changedWhatever:(NSNotification *)notification
{
    // Handle notification
}

#pragma mark - Public Methods

#pragma mark - Private Methods

#pragma mark - Protocols & Delegates

@end

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

Other Objective-C Style Guides

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

View on GitHub


iOS Coding Best Practices

File Structure

MyApp Files

MyModel.h

Description

MyModel header file. Header files contain class, type, function, properties, and constant declarations.

Documentation

Learning Objective-C: A Primer

NSObject Class Reference

NSObject Protocol Reference

MyModel.m

Description

MyModel source file. Source files can contain both Objective-C and C code, implement the methods declared in the header file and extended or inherited class methods.

Documentation

Learning Objective-C: A Primer

NSObject Class Reference

NSObject Protocol Reference

MyApp.xcdatamodeld

Description

Used by Core Data, groups versions of the model, each represented by an individual .xcdatamodel file, and an Info.plist file that contains the version information.

Documentation

Core Data Model Versioning and Data Migration Programming Guide

MyAppDelegate.h

Description

MyAppDelegate header file. Header files contain class, type, function, properties, and constant declarations.

Documentation

iOS App Programming Guide

UIApplication Class Reference

UIApplicationDelegate Protocol Reference

MyAppDelegate.m

Description

MyAppDelegate source file. Handle state transitions within the app. For example, this object is responsible for launch-time initialization and handling transitions to and from the background.

Documentation

iOS App Programming Guide

UIApplication Class Reference

UIApplicationDelegate Protocol Reference

Recommended code


//  MyAppDelegate.m
void uncaughtExceptionHandler(NSException *exception)
{
  NSLog(@"Exception: %@, %@", exception, [exception callStackSymbols]);
}

void signalHandler(int signal)
{
  NSLog(@"Signal: %d", signal);
}

- (void)setUncaughtExceptionHandler
{
  NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
}

- (void)setSignalHandler
{
  struct sigaction signalAction;
  memset(&signalAction, 0, sizeof(signalAction));
  signalAction.sa_handler = signalHandler;
  sigemptyset(&signalAction.sa_mask);
  signalAction.sa_flags = 0;
  sigaction(SIGABRT, &signalAction, NULL);
  sigaction(SIGILL, &signalAction, NULL);
  sigaction(SIGBUS, &signalAction, NULL);
  sigaction(SIGFPE, &signalAction, NULL);
  sigaction(SIGSEGV, &signalAction, NULL);
  sigaction(SIGTRAP, &signalAction, NULL);
  sigaction(SIGPIPE, &signalAction, NULL);
}

MyViewController.h

Description

MyViewController header file. Header files contain class, type, function, properties, and constant declarations.

Documentation

View Controller Programming Guide for iOS

UIViewController Class Reference

MyViewController.m

Description

MyViewController source file. Source files can contain both Objective-C and C code, implement the methods declared in the header file and extended or inherited class methods.

Documentation

View Controller Programming Guide for iOS

UIViewController Class Reference

MyStoryboard.storyboard

Description

A storyboard represents the screens in an app and the transitions between them.

Documentation

Your Second iOS App: Storyboards

UIStoryboard Class Reference

MyStoryboard-568h.storyboard

Description

A storyboard represents the screens in an app and the transitions between them. For 4-inch Retina Display.

Documentation

Your Second iOS App: Storyboards

UIStoryboard Class Reference

Recommended code


//  MyAppDelegate.m - application:didFinishLaunchingWithOptions:
NSString *storyboardName;
if ([[UIScreen mainScreen] bounds].size.height == 568) storyboardName = @"MyStoryboard-568h";
else storyboardName = @"MyStoryboard";

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.rootViewController = [[UIStoryboard storyboardWithName:storyboardName bundle:nil] instantiateInitialViewController];
[self.window makeKeyAndVisible];

Default.png

Description

To enhance the user’s experience at app launch, you must provide at least one launch image. iOS displays this image instantly when the user starts your app and until the app is fully ready to use. As soon as your app is ready for use, your app displays its first screen, replacing the launch placeholder image.

Documentation

iOS Human Interface Guidelines

Default@2x.png

Description

To enhance the user’s experience at app launch, you must provide at least one launch image. iOS displays this image instantly when the user starts your app and until the app is fully ready to use. As soon as your app is ready for use, your app displays its first screen, replacing the launch placeholder image. For Retina Display.

Documentation

iOS Human Interface Guidelines

Default-568h@2x.png

Description

To enhance the user’s experience at app launch, you must provide at least one launch image. iOS displays this image instantly when the user starts your app and until the app is fully ready to use. As soon as your app is ready for use, your app displays its first screen, replacing the launch placeholder image. For 4-inch Retina Display.

Documentation

iOS Human Interface Guidelines

Localizable.strings

Description

Default strings file. You can localize it in the Project Navigator and add new languages to your project.

Documentation

Resource Programming Guide

InfoPlist.strings

Description

Contains individual keys you want localized and the appropriately translated value.

Documentation

Information Property List Key Reference

MyApp.entitlements

Description

Set entitlement values in order to enable iCloud, push notifications, and App Sandbox.

Documentation

Entitlement Key Reference

MyApp-Info.plist

Description

App information property list file, comes preconfigured with keys that every information property list should have, like the app name.

Documentation

Information Property List Key Reference

main.m

Description

The main function in main.m calls the UIApplicationMain function within an autorelease pool.

Documentation

Start Developing iOS Apps Today

MyApp-Prefix.pch

Description

Add general imports or declare general project variables in this file.

Documentation

SDK Compatibility Guide

Defaults.plist

Description

You can declare the default values of NSUserDefaults on it.

Recommended code


//  MyAppDelegate.m - application:didFinishLaunchingWithOptions:
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Defaults" ofType:@"plist"]]];

Settings.bundle

Description

This bundle contains one or more Settings page files that describe the individual pages of preferences. It may also include other support files needed to display your preferences, such as images or localized strings.

Documentation

Preferences and Settings Programming Guide

MyAppTests.h

Description

MyAppTests header file. Header files contain class, type, function, properties, and constant declarations.

Documentation

Xcode Unit Testing Guide

MyAppTests.m

Description

MyAppTests source file. Source files can contain both Objective-C and C code, implement the methods declared in the header file and extended or inherited class methods.

Documentation

Xcode Unit Testing Guide

MyAppTests-Info.plist

Description

MyAppTests information property list file, comes preconfigured with keys that every information property list should have.

Documentation

Information Property List Key Reference

Recommended 3rd Party Frameworks

futuretap/InAppSettingsKit

Allows settings to be in-app in addition to being in the Settings app.

arashpayan/appirater

A utility that reminds your iPhone app's users to review the app.

ArtSabintsev/Harpy

Notify users when a new version of your iOS app is available, and prompt them with the App Store link.

a2/MKiCloudSync

Sync your NSUserDefaults to iCloud automatically. (Alexsander Akers fork)

AFNetworking/AFNetworking

A delightful iOS and OS X networking framework.

rs/SDWebImage

Asynchronous image downloader with cache support with an UIImageView category.

jdg/MBProgressHUD

Displays a translucent HUD with an indicator and/or labels while work is being done in a background thread.

myell0w/MTStatusBarOverlay

Custom status bar overlay seen in Apps like Reeder, Evernote and Google Mobile App. WARNING: iOS Human Interface Guidelines doesn't recommend an overlay on top of the UIStatusBar.

AlexBarinov/UIBubbleTableView

Cocoa UI component for chat bubbles with avatars and images support.

Moped/MPNotificationView

An in-app notification view that mimics the iOS 6 notification views which appear above the status bar.

View on GitHub