Skip to content

netcosports/objective-c-style-guide

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 

Repository files navigation

Objective-C Style Guide

This style guide outlines the coding conventions of the iOS team. The reason we made this style guide was so that we could keep our code nice and consistent - even though we have many different developers working on the projects. I welcome your feedback in issues and pull requests.

This style guide is based on Coding Guidelines for Cocoa.

Credits

I would like to thank the creators of the Ray Wenderlich and New York Times Objective-C Style Guides. This style guide provided a solid starting point for this guide to be created and based upon.

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.

Preferred:

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

Not Preferred:

[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 on the same line as the statement but close on a new line.

Preferred:

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

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;

If it's possible try to reduce nesting.

Preferred:

if (error) {
    return NO;
}
// Do something.
return YES;

Not Preferred:

if (!error) {
    // Do something.
    return YES;
}
return NO;

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

Preferred:

result = a > b ? x : y;

Not Preferred:

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.

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

Abbreviations and Acronyms

In general, you shouldn’t abbreviate names when you design your programmatic interface. However, there are abbreviations in Apple docs which are either well established or have been used in the past (URL, HTTP and etc).

Preferred:

@property (nullable, readonly, copy) NSString *URLString;
+ (NSURL *)URLWithDataRepresentation:(NSData *)data;

Not Preferred:

@property (nullable, readonly, copy) NSString *urlString;
+ (NSURL *)urlWithDataRepresentation:(NSData *)data;

Methods

In method signatures, there should be a space after the scope (- or + symbol). There should be a space between the method segments.

Preferred:

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

Variables

Variables should be named descriptively, with the variable’s name clearly communicating what the variable is and pertinent information a programmer needs to use that value properly.

Preferred:

  • NSString *title: It is reasonable to assume a “title” is a string.
  • NSString *titleHTML: This indicates a title that may contain HTML which needs parsing for display. “HTML” is needed for a programmer to use this variable effectively.
  • NSAttributedString *titleAttributedString: A title, already formatted for display. AttributedString hints that this value is not just a vanilla title, and adding it could be a reasonable choice depending on context.
  • NSDate *now: No further clarification is needed.
  • NSDate *lastModifiedDate: Simply lastModified can be ambiguous; depending on context, one could reasonably assume it is one of a few different types.
  • NSURL *URL vs. NSString *URLString: In situations when a value can reasonably be represented by different classes, it is often useful to disambiguate in the variable’s name.
  • NSString *releaseDateString: Another example where a value could be represented by another class, and the name can help disambiguate.

Single letter variable names should be avoided except as simple counter variables in loops.

Asterisks indicating a type is a pointer should be “attached to” the variable name. For example, NSString *text not NSString* text or NSString * text, except in the case of constants (NSString * const NYTConstantString).

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, see Apple’s docs on using accessor methods in initializer methods and dealloc.

Preferred:

@interface Section: NSObject

@property (nonatomic) NSString *headline;

@end

Not Preferred:

@interface Section : NSObject {
    NSString *headline;
}

Variable Qualifiers

When it comes to the variable qualifiers introduced with ARC, the qualifier (__strong, __weak, __unsafe_unretained, __autoreleasing) should be placed before the variable type for better readability, e.g., __weak NSString *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.

Preferred:

UIButton *settingsButton;

Not

UIButton *setBut;

A two or three letter prefix (e.g., NST) should always be used for class names and constants (except static and local constants for internal use). Constants should be camel-case with all words capitalized and prefixed by the related class name for clarity. A two letter prefix (e.g., NS) is reserved for use by Apple.

Preferred:

static const NSTimeInterval NSTArticleViewControllerNavigationFadeAnimationDuration = 0.3f;

Not Preferred:

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.

Preferred:

@synthesize descriptiveVariableName = _descriptiveVariableName;

Not Preferred:

id varnm;

Categories

Categories may be used to concisely segment functionality and should be named to describe that functionality.

Preferred:

@interface UIViewController (NSTMediaPlaying)
@interface NSString (NSStringEncodingDetection)

Not Preferred:

@interface Advertisement (private)
@interface NSString (NSTAdditions)

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.

Comments should be capitalized.

Preferred:

/**
 * Method explanation.
 * 
 * @param alpha Represents transparency of an object. It varies between 0.0f and 1.0f.
 */
- (void)doSomethingWithAlpha:(CGFloat)alpha
{
    // This is very useful comment.
    ...
}

Not Preferred:

- (void)doSomething
{
    // not capitalized
    /* Commented with block. */
    ...
}

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
{
    // Call super initializer or the designated initializer.
    self = [super init];
    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.

Preferred:

NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"];
NSDictionary *productManagers = @{@"iPhone" : @"Kate", @"iPad" : @"Kamal", @"Mobile Web" : @"Bill"};
NSNumber *shouldUseLiterals = @YES;
NSNumber *buildingZIPCode = @(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 *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.

Preferred:

CGRect frame = self.view.frame;

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

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;

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.

Preferred:

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

static const CGFloat NYTImageThumbnailHeight = 50.0;

Not Preferred:

#define CompanyName @"The New York Times Company"

#define thumbnailHeight 2

Enumerated Types

When using enums, use the new fixed underlying type specification, which provides stronger type checking and code completion. The SDK 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.

Preferred:

@interface NYTAdvertisement ()

@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 lower case string with separated by underscore: 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.

Preferred:

  • refresh_bar_button_item / refresh_bar_button_item@2x and refresh_bar_button_item_selected / refresh_bar_button_item_selected@2x
  • article_navigation_bar_white / article_navigation_bar_white@2x and article_navigation_bar_black_selected / article_navigation_bar_black_selected@2x.

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

Booleans

Never compare something directly to YES, because YES is defined as 1, and a BOOL in Objective-C is a CHAR type that is 8 bits long (so a value of 11111110 will return NO if compared to YES).

For an object pointer:

if (!someObject) {
}

if (someObject == nil) {
}

For a BOOL value:

if (isAwesome)
if (!someNumber.boolValue)
if (someNumber.boolValue == NO)

Not Preferred:

if (isAwesome == YES) // Never do this.

If the name of a BOOL property is expressed as an adjective, the property’s name can omit the is prefix but should specify the conventional name for the getter.

Preferred:

@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;
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
      sharedInstance = [[[self class] alloc] init];
   });
   return sharedInstance;
}

This will prevent possible and sometimes frequent crashes.

Imports

If there is more than one import statement, group the statements together. Commenting each group is optional.

Note: For modules use the @import syntax.

// Frameworks.
@import QuartzCore;

// Models.
#import "NYTUser.h"

// Views.
#import "NYTButton.h"
#import "NYTUserView.h"

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:

Uncrustify

##How to install

  1. Install packet manager: Homebrew (http://brew.sh/) or MacPorts (https://www.macports.org/).
  2. Install uncrustify: brew install uncrustify or port install uncrustify.

Or

https://github.com/bengardner/uncrustify

For edit config file you may use https://github.com/ryanmaxwell/UncrustifyX.

##XCode

Script

Add new Run Script and paste:

///////

UNCRUSTIFY="uncrustify" CONFIG=$HOME"/.uncrustify/uncrustify.cfg" SOURCE_LANGUAGE="AUTO"

for file in $(find . -name '.m' -o -name '.mm' -o -name '*.h') do "$UNCRUSTIFY" -c "$CONFIG" --no-backup $file $language_option done

///////

UNCRUSTIFY - uncrustify location CONFIG - config file location

Install XCode Uncrustify Plugin

https://github.com/benoitsan/BBUncrustifyPlugin-Xcode

For use custom config file - create ".uncrustify" directory in you user directory and paste custom config file "uncrustify.cfg". Open Edit - Format Code - BBUncrustifyPlugin Preferences and change Clang Style to Custom Style(File).

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published