Objective-C Coding Style

PUBLISHED ON MAR 19, 2017 / 2 MIN READ — CODE

My code convention for Objective-C inspired by Sources

Table of Contents

Code Organization

Use #pragma mark - to categorize methods in functional groupings.

#pragma mark - Lifecycle

- (instancetype)init {}
- (void)viewDidLoad {}
- (void)viewWillAppear:(BOOL)animated {}
- (void)didReceiveMemoryWarning {}

#pragma mark - Custom Accessors

- (void)setCustomProperty:(id)value {}
- (id)customProperty {}

#pragma mark - Public

- (void)publicMethod {}

#pragma mark - Private

- (void)privateMethod {}

#pragma mark - Protocol conformance
#pragma mark - UITextFieldDelegate
#pragma mark - UITableViewDataSource
#pragma mark - UITableViewDelegate

#pragma mark - IBActions

- (IBAction)submitData:(id)sender {}

Spacing

  • Indent using 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 be used to separate functionality (though often this can indicate an opportunity to split the method into several, smaller methods). In methods with long or verbose names, a single line of whitespace may be used to provide visual separation before the method’s body.
  • @synthesize and @dynamic should each be declared on new lines in the implementation.

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, only with a single condition.

For example:

result = a > b ? x : y;

Not:

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

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;

The beginning bracket should be in the same line of the method signature

For example:

- (void)setExampleText:(NSString *)text image:(UIImage *)image {    
    // Code...
}

Variables

TO-DO

Naming

TO-DO

Comments

TO-DO

Constants

TO-DO

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

Sources

This guide has been built taking inspiration from the following sources:

comments powered by Disqus