Skip to content

Antol/objective-c-style-guide

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 

Repository files navigation

Objective-C Style Guide

TL;DR

For example: h-file

//
//  AACheckboxView.h
//  amazingProject
//
//  Created by Anatoliy Peshkov on 15/08/2016.
//  Copyright © 2016 SomeCompany. All rights reserved.
//

#import "PMNibLinkableView.h"
@class AACheckboxView;
@class AASomeObject;
@protocol SomeProtocol;

FOUNDATION_EXPORT NSString *const kAACheckboxViewStringExternConstant;

@protocol AACheckboxViewDelegate <NSObject>
- (void)somethingVeryImportantHappenedInCheckboxView:(AACheckboxView *)checkboxView 
@optional
- (void)checkboxView:(AACheckboxView *)checkboxView userDidChangeState:(BOOL)isSelected;
@end

@interface AACheckboxView : PMNibLinkableView
@property (nonatomic, weak) id<AACheckboxViewDelegate> delegate;
@property (nonatomic, assign, readonly) BOOL isSelected;
- (void)select:(void (^)(NSError *error))completion;
- (void)deselect;
@end

For example: m-file

//
//  AACheckboxView.m
//  amazingProject
//
//  Created by Anatoliy Peshkov on 15/08/2016.
//  Copyright © 2016 SomeCompany. All rights reserved.
//

#import "AACheckboxView.h"
#import "AAActionButtonCard.h"
#import "AACommonUtils.h"
#import "AANetworkServicesAssembly.h"
#import <Fabric/Fabric.h>
#import <Crashlytics/Crashlytics.h>
#import "AASomeObject.h"
#import "SomeProtocol.h"

NSString *const kAACheckboxViewStringExternConstant = @"SomeStringValue";
static NSString *const kAACheckboxViewNotificationKey = @"MyThingNotificationKey";
static const NSTimeInterval kAACheckboxViewFadeAnimationDuration = 0.3;


typedef NS_ENUM(NSInteger, AARequestState) {
    AARequestStateInactive,
    AARequestStateLoading
};


@interface AACheckboxView () <UITableViewDelegate, UITableViewDatasource, AAMagicProtocol1, AAMagicProtocol2,
                              AAMagicProtocol3, AAMagicProtocol4, AAMagicProtocol5>
@property (nonatomic, weak) IBOutlet AALocalizedLabel *titleLabel;
@property (nonatomic, weak) IBOutlet UIImageView *tickImageView;

@property (nonatomic, assign) BOOL isSelected;
@property (nonatomic, strong) NSNumber *tempVariable;
@property (nonatomic, copy)   NSString *headline;
@end


@implementation AACheckboxView

- (instancetype)init {
    self = [super init];
    if (self) {
        self.tempVariable = [AAVeryMeaningfulClassName objectWithParameter:foo 
                                                         longlongParameter:bar
                                                                     short:buz
                                         veryVeryVeryVeryLongParameterName:longParamName];
    }
    else {
        NSAssert([UIApplication sharedApplication].delegate, @"Some debug message which will not be visible fo user");
    }
    return self;
}

#pragma mark - Actions

- (IBAction)actionButtonTapped:(id)sender {
    self.backgroundColor = [UIColor orangeColor];
    [UIApplication sharedApplication].delegate = self;
  
    id tempVar = (a > b)? object.getSomeStuff : @13.5;
    [self changeState];

    NSArray *assemblies = @[@"EJApplicationAssembly",
                            @"EJMessageInboxAssembly",
                            @"EJContentManagerAssembly",
                            @"EJDeepLinkAssembly",
                            @"EJCoreAssembly",
                            @"EJConciergeLiveAssembly",
                            @"EJAnalyticsAssembly",
                            @"EJForceUpgradeAssembly",
                            @"EJSSLCheckerAssembly",
                            @"EJNetworkServicesAssembly",
                            @"EJApplePayAssembly"];
}

#pragma mark - UITableViewDatasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.passengers.count;
}

#pragma mark - Private

- (void)changeState {
    if (!self.headline &&
        longLongLongLongLongLongLongCondition && 
        bigBigBigVariableName > 1234567890 ||
        variable.someProperty.something.isAvailable &&
        [veryVeryVeryVeryLongParameterName isEqual:veryVeryVeryVeryLongParameterName])
    {
        self.tempVariable = @YES;
    }

    CGRect frame = self.view.frame;

    CGFloat x = CGRectGetMinX(frame);
    CGFloat y = CGRectGetMinY(frame);
    CGFloat width = CGRectGetWidth(frame);
    CGFloat height = CGRectGetHeight(frame);
}

- (void)fetchSomeData:(void(^)(BOOL success))compleition {
    @weakify(self)
    [self.restClient doGET:@"triam/param" completion:^(id result, NSError *error) {
      @strongify(self)
      [result doSomeThing];

      [self.restClient
       doGET:@"triam/param"
       params:@{@"long_long_long_long_json_key": @1234567890123456}
       headers:[someVeryUsefulObject generateHeadersForGetrequest]
       completion:^(id result, NSError *error) {
           @strongify(self)
           self.headline = result;
           [result doSomeThing];
       }];
    }];
}

@end

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

Dot-Notation Syntax

Dot-notation should always be used for accessing and mutating properties. Bracket notation is preferred in all other instances. Calling of getter methods without parameters also should be done through dot notation. If method had side effects it is not a getter method

For example:

view.backgroundColor = [UIColor orangeColor];
[UIApplication sharedApplication].delegate;
object.getSomeStuff;
[object changeState];

Not:

[view setBackgroundColor:[UIColor orangeColor]];
UIApplication.sharedApplication.delegate;
[object getSomeStuff];
object.changeSate;

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 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.
  • @class, @protocol, @synthesize and @dynamic should each be declared on new lines in the implementation.

Word wrapping

Every code line should not be longer than 140 signs. If method name is too long it should be broken in few lines. In this case every parameter should be on separate line. If condition is too long it also should be broken in few lines in places after topmost logical operators and braces should be placed on next line. Or even better - condition should be assigned to variable.

For example:

APVeryMeaningfulClassName *variable = [APVeryMeaningfulClassName objectWithParameter:foo 
                                                                   longlongParameter:bar
                                                                               short:buz
                                                   veryVeryVeryVeryLongParameterName:longParamName];

BOOL isChecked = longLongLongLongLongLongLongCondition && 
                 bigBigBigVariableName > 1234567890 ||
                 variable.someProperty.something.isAvailable &&
                 [veryVeryVeryVeryLongParameterName isEqual:veryVeryVeryVeryLongParameterName];
if (isChecked) {
    //Do something
}

or

if (longLongLongLongLongLongLongCondition && 
    bigBigBigVariableName > 1234567890 ||
    variable.someProperty.something.isAvailable &&
    [veryVeryVeryVeryLongParameterName isEqual:veryVeryVeryVeryLongParameterName])
{
    //Do something
}

Not:

APVeryMeaningfulClassName *variable = [APVeryMeaningfulClassName objectWithParameter:foo longlongParameter:bar short:buz veryVeryVeryVeryLongParameterName:veryVeryVeryVeryLongParameterName];

APVeryMeaningfulClassName *variable = [APVeryMeaningfulClassName objectWithParameter:foo longlongParameter:bar short:buz
                                                   veryVeryVeryVeryLongParameterName:longParamName];

if (longLongLongLongLongLongLongCondition &&  bigBigBigVariableName > 1234567890 || variable.someProperty.something.isAvailable && [veryVeryVeryVeryLongParameterName isEqual:veryVeryVeryVeryLongParameterName]) {
    //Do something
}

if (longLongLongLongLongLongLongCondition && 
    bigBigBigVariableName > 1234567890 ||
    variable.someProperty.something.isAvailable &&
    [veryVeryVeryVeryLongParameterName isEqual:veryVeryVeryVeryLongParameterName]) {
    THisIsAction *butYouCanThink = [ThatItIsStill condition];
}

To siply check length of strings it is recommended to turn on "Page guide" in Xcode (Xcode -> Preferences -> Text Editing -> Editing -> Page guide at column: (140))

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. The condition in Ternary operator should be sorounded with brackets

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;

If method has block as only parameter the name of method should not have any adition like 'completionBlock'. Parameter should be named 'compleition'. For example:

- (void)fetchSomeData:(void(^)(BOOL success))compleition;

Not:

- (void)fetchSomeDataWithCompletionBlock:(void(^)(BOOL success))compleitionBlock;

Calling of methods with block as parameter should give the impression of single indent. If method or parameters is too long to fit in 140 signs it should be wrapped as shown in example - every parameter on new line with 1 space intend, block intended usually from last parameter position.

For example:

[self.restClient doGET:@"triam/param" completion:^(id result, NSError *error) {
  [result doSomeThing];
}];

[self.restClient
 doGET:@"triam/param"
 params:@{@"long_long_long_long_json_key": @1234567890123456}
 headers:[someVeryUsefulObject generateHeadersForGetrequest]
 completion:^(id result, NSError *error) {
   [result doSomeThing];
 }];

Not:

[self.restClient doGET:@"triam/param" params:@{@"long_long_long_long_json_key": @1234567890123456} headers:[someVeryUsefulObject generateHeadersForGetrequest] completion:^(id result, NSError *error) {
  [result doSomeThing];
}];

[self.restClient doGET:@"triam/param" 
                params:@{@"long_long_long_long_json_key": @1234567890123456} 
               headers:[someVeryUsefulObject generateHeadersForGetrequest] 
            completion:^(id result, NSError *error) {
  [result doSomeThing];
}];

[self.restClient doGET:@"triam/param" 
                params:@{@"long_long_long_long_json_key": @1234567890123456} 
               headers:[someVeryUsefulObject generateHeadersForGetrequest] 
            completion:^(id result, NSError *error) {
              [result doSomeThing];
            }];

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. 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 NYTSection: NSObject

@property (nonatomic, copy) NSString *headline;

@end

Not:

@interface NYTSection : NSObject {
    NSString *headline;
}

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. NYT) 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 and 'k' letter for clarity.

For example:

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

init methods should be placed at the top of the implementation. 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;

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

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.

For example:

static NSString * const kNYTAboutViewControllerCompanyName = @"The New York Times Company";

static const CGFloat kNYTImageThumbnailHeight = 50.0;

Not:

#define CompanyName @"The New York Times Company"

#define thumbnailHeight 2

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, NYTAdRequestState) {
    NYTAdRequestStateInactive,
    NYTAdRequestStateLoading
};

Bitmasks

When working with bitmasks, use the NS_OPTIONS macro.

Example:

typedef NS_OPTIONS(NSUInteger, NYTAdCategory) {
  NYTAdCategoryAutos      = 1 << 0,
  NYTAdCategoryJobs       = 1 << 1,
  NYTAdCategoryRealState  = 1 << 2,
  NYTAdCategoryTechnology = 1 << 3
};

Private Properties

Private properties should be declared in class extensions (anonymous categories) in the implementation file of a class. Named categories (such as 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

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)

Singletons

Direct usege of Singletons should be avoided! Use Typhoone injection to property in this case. If it is not possible for some reason, should be used Typhoon assembly directly.

Xcode project

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:

About

The Objective-C Style Guide

Resources

License

Stars

Watchers

Forks

Packages

No packages published