Style guide & coding conventions for Objective-C projects

Overview

This repository is no longer active.


These guidelines build on Apple's existing Coding Guidelines for Cocoa. Unless explicitly contradicted below, assume that all of Apple's guidelines apply as well.

Whitespace

  • Tabs, not spaces.
  • End files with a newline.
  • Make liberal use of vertical whitespace to divide code into logical chunks.
  • Don’t leave trailing whitespace.
    • Not even leading indentation on blank lines.

Documentation and Organization

  • All method declarations should be documented.
  • Comments should be hard-wrapped at 80 characters.
  • Comments should be Tomdoc-style.
  • Document whether object parameters allow nil as a value.
  • Use #pragma marks to categorize methods into functional groupings and protocol implementations, following this general structure:
#pragma mark Properties

@dynamic someProperty;

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

#pragma mark Lifecycle

+ (instancetype)objectWithThing:(id)thing {}
- (instancetype)init {}

#pragma mark Drawing

- (void)drawRect:(CGRect) {}

#pragma mark Another functional grouping

#pragma mark GHSuperclass

- (void)someOverriddenMethod {}

#pragma mark NSCopying

- (id)copyWithZone:(NSZone *)zone {}

#pragma mark NSObject

- (NSString *)description {}

Declarations

  • Never declare an ivar unless you need to change its type from its declared property.
  • Don’t use line breaks in method declarations.
  • Prefer exposing an immutable type for a property if it being mutable is an implementation detail. This is a valid reason to declare an ivar for a property.
  • Always declare memory-management semantics even on readonly properties.
  • Declare properties readonly if they are only set once in -init.
  • Don't use @synthesize unless the compiler requires it. Note that optional properties in protocols must be explicitly synthesized in order to exist.
  • Declare properties copy if they return immutable objects and aren't ever mutated in the implementation. strong should only be used when exposing a mutable object, or an object that does not conform to .
  • Avoid weak properties whenever possible. A long-lived weak reference is usually a code smell that should be refactored out.
  • Instance variables should be prefixed with an underscore (just like when implicitly synthesized).
  • Don't put a space between an object type and the protocol it conforms to.
@property (attributes) id
    object;
@property (nonatomic, strong) 
   NSObject
   
     *object;
   
  
  • C function declarations should have no space before the opening parenthesis, and should be namespaced just like a class.
void GHAwesomeFunction(BOOL hasSomeArgs);
  • Constructors should generally return instancetype rather than id.
  • Prefer helper functions (such as CGRectMake()) to C99 struct initialiser syntax.
  CGRect rect = CGRectMake(3.0, 12.0, 15.0, 80.0);

Expressions

  • Don't access an ivar unless you're in -init, -dealloc or a custom accessor.
  • Use dot-syntax when invoking idempotent methods, including setters and class methods (like NSFileManager.defaultManager).
  • Use object literals, boxed expressions, and subscripting over the older, grosser alternatives.
  • Comparisons should be explicit for everything except BOOLs.
  • Prefer positive comparisons to negative.
  • Long form ternary operators should be wrapped in parentheses and only used for assignment and arguments.
Blah *a = (stuff == thing ? foo : bar);
  • Short form, nil coalescing ternary operators should avoid parentheses.
Blah *b = thingThatCouldBeNil ?: defaultValue;
  • Separate binary operands with a single space, but unary operands and casts with none:
void *ptr = &value + 10 * 3;
NewType a = (NewType)b;

for (int i = 0; i < 10; i++) {
    doCoolThings();
}

Control Structures

  • Always surround if bodies with curly braces if there is an else. Single-line if bodies without an else should be on the same line as the if.
  • All curly braces should begin on the same line as their associated statement. They should end on a new line.
  • Put a single space after keywords and before their parentheses.
  • Return and break early.
  • No spaces between parentheses and their contents.
if (somethingIsBad) return;

if (something == nil) {
	// do stuff
} else {
	// do other stuff
}

Exceptions and Error Handling

  • Don't use exceptions for flow control.
  • Use exceptions only to indicate programmer error.
  • To indicate errors, use an NSError ** argument or send an error on a ReactiveCocoa signal.

Blocks

  • Blocks should have a space between their return type and name.
  • Block definitions should omit their return type when possible.
  • Block definitions should omit their arguments if they are void.
  • Parameters in block types should be named unless the block is initialized immediately.
void (^blockName1)(void) = ^{
    // do some things
};

id (^blockName2)(id) = ^ id (id args) {
    // do some things
};

Literals

  • Avoid making numbers a specific type unless necessary (for example, prefer 5 to 5.0, and 5.3 to 5.3f).
  • The contents of array and dictionary literals should have a space on both sides.
  • Dictionary literals should have no space between the key and the colon, and a single space between colon and value.
NSArray *theStuff = @[ @1, @2, @3 ];

NSDictionary *keyedStuff = @{ GHDidCreateStyleGuide: @YES };
  • Longer or more complex literals should be split over multiple lines (optionally with a terminating comma):
NSArray *theStuff = @[
    @"Got some long string objects in here.",
    [AndSomeModelObjects too],
    @"Moar strings."
];

NSDictionary *keyedStuff = @{
    @"this.key": @"corresponds to this value",
    @"otherKey": @"remoteData.payload",
    @"some": @"more",
    @"JSON": @"keys",
    @"and": @"stuff",
};

Categories

  • Categories should be named for the sort of functionality they provide. Don't create umbrella categories.
  • Category methods should always be prefixed.
  • If you need to expose private methods for subclasses or unit testing, create a class extension named Class+Private.
Comments
  • Proposed number style

    Proposed number style

    This has come up a few times.

    I generally think any unnecessary type in a number literal is silly, because it just makes it more fragile and more work to change later (if the type of the variable, constant, etc. changes). I also prefer reading this:

    CGRect rect = { .x = 5, .y = 10, .width = 50, .height = 50 };
    

    over this:

    CGRect rect = { .x = 5.0, .y = 10.0, .width = 50.0, .height = 50.0 };
    

    And I think we can all agree that @alanjrogers' 5. is horrific. :wink:

    opened by jspahrsummers 13
  • C99 Struct Initialisers

    C99 Struct Initialisers

    Document a preference for verbose struct initialisers rather than helper functions. These are easier to read and allow structs to be initialise with any sub-structs rather than having to use their members explicitly.

    opened by dannygreg 9
  • Vertical whitespace

    Vertical whitespace

    This is strictly an aesthetic thing, but I generally find more vertical whitespace to aid readability, and after a control structure is one of the most effective places to do it.

    opened by jspahrsummers 8
  • Exception conventions

    Exception conventions

    There’s nothing on exceptions in https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html so wanted to discuss them here

    /cc @github/objective-c

    opened by keithduncan 7
  • Always declare private methods

    Always declare private methods

    Recent versions of Xcode include some changes to the compiler that make it possible to invoke methods in an implementation regardless of if they are declared and regardless of the method definition order.

    When I'm reading an implementation that I'm unfamiliar with the first thing I do is check the private class extension at the top of the implementation file. While it's no longer required, I feel that the benefits of having all of your methods in one place is worth it. It helps avoid leaving around abandoned methods and avoids having to initially scan through the entire implementation. Plus you can put all of your private method docs in one place.

    opened by jackhl 5
  • Update README.md

    Update README.md

    Usually the #pragma mark has a "-", to make the description easier to read. Maybe I'm wrong, but I've always seen only this format of #pragma mark

    opened by scamps88 3
  • Don’t leave trailing whitespace

    Don’t leave trailing whitespace

    This is intended to be a descriptive, rather than prescriptive change; several of us appear to have our editors configured to strip trailing whitespace, and since I’m sick of seeing whitespace changes in diffs, I suggest we standardize.

    I committed (and pushed!) this straight to master initially, suspiciously like an idiot might, hence why the commit here is a revert of a revert.

    opened by robrix 3
  • Changed dot-syntax usage a bit

    Changed dot-syntax usage a bit

    OK object.name = @"Github"; object.name;

    NOT OK object.doSomething; object.copy; AClass.makeSomeStuff; AClass.alloc.init; [AClass.alloc initWithName:@"Octocat"];

    opened by supermarin 3
  • Block arguments should always be named.

    Block arguments should always be named.

    Block declaration arguments should always include variable names to follow the Objective-C style of named arguments.

    Also what's your stance on typedef'ing blocks? I'm somewhat against it just because you can't easily determine the block arguments by command-clicking on a method or quickly looking at a header file.

    opened by jackhl 3
  • Variable/property naming style

    Variable/property naming style

    Variable and property names should begin with a lowercase letter and then proceed by uppercasing the first letter of each additional word (camel-case). Avoid acronyms and abbreviations.

    opened by jackhl 3
  • Constructor return type

    Constructor return type

    Constructors should use instancetype instead of id as their return type because methods that do not begin with one of the checked keywords (alloc, init, new, etc) will not get the same stricter type checking.

    See http://clang.llvm.org/docs/LanguageExtensions.html#objc_instancetype

    opened by jackhl 3
Owner
GitHub
How people build software.
GitHub
A style guide that outlines the coding conventions for raywenderlich.com

The official raywenderlich.com Objective-C style guide. This style guide outlines the coding conventions for raywenderlich.com. Introduction The reaso

raywenderlich 3.1k Jan 2, 2023
The Objective-C Style Guide used by The New York Times

NYTimes Objective-C Style Guide This style guide outlines the coding conventions of the iOS teams at The New York Times. We welcome your feedback in i

The New York Times 5.8k Jan 6, 2023
The official Swift style guide for raywenderlich.com.

The Official raywenderlich.com Swift Style Guide. Updated for Swift 5 This style guide is different from others you may see, because the focus is cent

raywenderlich 12.5k Dec 30, 2022
A style guide for Swift.

Table Of Contents Overview Linter Standards Naming Conventions File Structure Types Statement Termination Variable Declaration Self Structs & Classes

Prolific Interactive 171 Oct 4, 2022
LinkedIn's Official Swift Style Guide

Swift Style Guide Make sure to read Apple's API Design Guidelines. Specifics from these guidelines + additional remarks are mentioned below. This guid

LinkedIn 1.4k Dec 13, 2022
A CSS-like style library for SwiftUI.

The missing CSS-like module for SwiftUI

hite 112 Dec 23, 2022
Theme handling macOS Appkit (Swift/Objective-C)

DSFAppearanceManager A class for simplifying macOS appearance values and detecting setting changes (Swift/Objective-C). Why? If you're performing cust

Darren Ford 8 Nov 1, 2022
Style guide & coding conventions for Swift projects

This repository is no longer active. A guide to our Swift style and conventions. This is an attempt to encourage patterns that accomplish the followin

GitHub 4.8k Jan 4, 2023
A style guide that outlines the coding conventions for raywenderlich.com

The official raywenderlich.com Objective-C style guide. This style guide outlines the coding conventions for raywenderlich.com. Introduction The reaso

raywenderlich 3.1k Jan 2, 2023
SwiftLint - A tool to enforce Swift style and conventions, loosely based on Swift Style Guide.

SwiftLint - A tool to enforce Swift style and conventions, loosely based on Swift Style Guide.

Realm 16.9k Dec 30, 2022
A tool to enforce Swift style and conventions.

SwiftLint A tool to enforce Swift style and conventions, loosely based on the now archived GitHub Swift Style Guide. SwiftLint enforces the style guid

Realm 16.9k Jan 9, 2023
The Objective-C Style Guide used by The New York Times

NYTimes Objective-C Style Guide This style guide outlines the coding conventions of the iOS teams at The New York Times. We welcome your feedback in i

The New York Times 5.8k Jan 6, 2023
Airbnb's Swift Style Guide.

Airbnb Swift Style Guide Goals Following this style guide should: Make it easier to read and begin understanding unfamiliar code. Make code easier to

Airbnb 1.8k Jan 3, 2023
LinkedIn's Official Swift Style Guide

Swift Style Guide Make sure to read Apple's API Design Guidelines. Specifics from these guidelines + additional remarks are mentioned below. This guid

LinkedIn 1.4k Jan 5, 2023
The Official raywenderlich.com Swift Style Guide.

The Official raywenderlich.com Swift Style Guide. Updated for Swift 5 This style guide is different from others you may see, because the focus is cent

raywenderlich 12.5k Jan 3, 2023
The official Swift style guide for raywenderlich.com.

The Official raywenderlich.com Swift Style Guide. Updated for Swift 5 This style guide is different from others you may see, because the focus is cent

raywenderlich 12.5k Dec 30, 2022
A style guide for Swift.

Table Of Contents Overview Linter Standards Naming Conventions File Structure Types Statement Termination Variable Declaration Self Structs & Classes

Prolific Interactive 171 Oct 4, 2022
LinkedIn's Official Swift Style Guide

Swift Style Guide Make sure to read Apple's API Design Guidelines. Specifics from these guidelines + additional remarks are mentioned below. This guid

LinkedIn 1.4k Dec 13, 2022
Signal Handling with more normal Swift conventions

SignalHandler Adds support for signal handlers in a fully swifty way. Why this over raw signal handling or other packages. Signal handler functions ar

Braden Scothern 2 Apr 3, 2022
JSPatch bridge Objective-C and Javascript using the Objective-C runtime. You can call any Objective-C class and method in JavaScript by just including a small engine. JSPatch is generally used to hotfix iOS App.

JSPatch 中文介绍 | 文档 | JSPatch平台 请大家不要自行接入 JSPatch,统一接入 JSPatch 平台,让热修复在一个安全和可控的环境下使用。原因详见 这里 JSPatch bridges Objective-C and JavaScript using the Object

bang 11.4k Jan 1, 2023