• This repository has been archived on 09/May/2023
  • Stars
    star
    5,848
  • Rank 6,933 (Top 0.2 %)
  • Language
  • License
    MIT License
  • Created over 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The Objective-C Style Guide used by The New York Times

[DEPRECATED]

NYTimes Objective-C Style Guide is deprecated. No more development will be taking place. Thanks for all your support!

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 issues and pull requests. Also, we’re hiring.

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:

This style guide conforms to IETF's RFC 2119. In particular, code which goes against the RECOMMENDED/SHOULD style is allowed, but should be carefully considered.

Table of Contents

Dot Notation Syntax

Dot notation is RECOMMENDED over bracket notation for getting and setting properties.

For example:

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

Not:

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

Spacing

  • Indentation MUST use 4 spaces. Never indent with tabs. Be sure to set this preference in Xcode.
  • Method braces and other braces (if/else/switch/while etc.) MUST open on the same line as the statement. Braces MUST 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 MAY separate functionality, though this inclination often indicates 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 MUST each be declared on new lines in the implementation.

Conditionals

Conditional bodies MUST 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 can 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 intent of the ternary operator, ? , is to increase clarity or code neatness. The ternary SHOULD only evaluate a single condition per expression. Evaluating multiple conditions is usually more understandable as an if statement or refactored into named 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, code MUST switch on the returned value and MUST NOT switch on the error variable.

For example:

NSError *error;
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 (- or + symbol). There SHOULD be a space between the method segments.

For example:

- (void)setExampleText:(NSString *)text image:(UIImage *)image;
  • Methods exceeding 80 characters SHOULD be represented like a form with a new line after each argument

For example:

- (void)setExampleText:(NSString *)text 
                 image:(UIImage *)image 
                 color:(UIColor *)color 
       alternativeText:(NSString *)altText;

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.

For example:

  • 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 are NOT RECOMMENDED, except as simple counter variables in loops.

Asterisks indicating a type is a pointer MUST 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.

For example:

@interface NYTSection : NSObject

@property (nonatomic) NSString *headline;

@end

Not:

@interface NYTSection : 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 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) MUST be used for class names and constants, however MAY be omitted for Core Data entity names. Constants MUST 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.

For example:

static const NSTimeInterval NYTArticleViewControllerNavigationFadeAnimationDuration = 0.3;

Not:

static const NSTimeInterval fadetime = 1.7;

Properties and local variables MUST be camel-case with the leading word being lowercase.

Instance variables MUST be camel-case with the leading word being lowercase, and MUST 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;

Categories

Categories are RECOMMENDED to concisely segment functionality and should be named to describe that functionality.

For example:

@interface UIViewController (NYTMediaPlaying)
@interface NSString (NSStringEncodingDetection)

Not:

@interface NYTAdvertisement (private)
@interface NSString (NYTAdditions)

Methods and properties added in categories MUST be named with an app- or organization-specific prefix. This avoids unintentionally overriding an existing method, and it reduces the chance of two categories from different libraries adding a method of the same name. (The Objective-C runtime doesn’t specify which method will be called in the latter case, which can lead to unintended effects.)

For example:

@interface NSArray (NYTAccessors)
- (id)nyt_objectOrNilAtIndex:(NSUInteger)index;
@end

Not:

@interface NSArray (NYTAccessors)
- (id)objectOrNilAtIndex:(NSUInteger)index;
@end

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 are NOT RECOMMENDED, 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 methods 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 initializer
    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, code MUST 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 RECOMMENDED 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 MUST be declared as static constants. Constants MAY be declared as #define when explicitly being used as a macro.

For example:

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

static const CGFloat NYTImageThumbnailHeight = 50.0;

Not:

#define CompanyName @"The New York Times Company"

#define thumbnailHeight 2

Enumerated Types

When using enums, the new fixed underlying type specification MUST be used; it 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, the NS_OPTIONS macro MUST be used.

Example:

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

Private Properties

Private properties SHALL be declared in class extensions (anonymous categories) in the implementation file of a class.

For example:

@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. Images 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 or Asset Catalog.

Booleans

Values MUST NOT be compared 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:

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

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

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 class] alloc] init];
    });

    return sharedInstance;
}

This will prevent possible and sometimes frequent crashes.

Imports

If there is more than one import statement, statements MUST be grouped together. Groups MAY be commented.

Note: For modules use the @import syntax.

// Frameworks
@import QuartzCore;

// Models
#import "NYTUser.h"

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

Protocols

In a delegate or data source protocol, the first parameter to each method SHOULD be the object sending the message.

This helps disambiguate in cases when an object is the delegate for multiple similarly-typed objects, and it helps clarify intent to readers of a class implementing these delegate methods.

For example:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

Not:

- (void)didSelectTableRowAtIndexPath:(NSIndexPath *)indexPath;

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.

Target Build Setting “Treat Warnings as Errors” SHOULD be enabled. 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:

More Repositories

1

covid-19-data

A repository of data on coronavirus cases and deaths in the U.S.
6,989
star
2

gizmo

A Microservice Toolkit from The New York Times
Go
3,753
star
3

Store

Android Library for Async Data Loading and Caching
Java
3,531
star
4

NYTPhotoViewer

A modern photo viewing experience for iOS.
Objective-C
2,847
star
5

pourover

A library for simple, fast filtering and sorting of large collections in the browser. There is a community-maintained fork that addresses a handful of post-NYT issues available via @hhsnopek's https://github.com/hhsnopek/pourover
JavaScript
2,393
star
6

kyt

Starting a new JS app? Build, test and run advanced apps with kyt 🔥
JavaScript
1,922
star
7

react-tracking

🎯 Declarative tracking for React apps.
JavaScript
1,876
star
8

ice

track changes with javascript
JavaScript
1,708
star
9

backbone.stickit

Backbone data binding, model binding plugin. The real logic-less templates.
JavaScript
1,641
star
10

library

A collaborative documentation site, powered by Google Docs.
JavaScript
1,143
star
11

openapi2proto

A tool for generating Protobuf v3 schemas and gRPC service definitions from OpenAPI specifications
Go
940
star
12

gziphandler

Go middleware to gzip HTTP responses
Go
857
star
13

svg-crowbar

Extracts an SVG node and accompanying styles from an HTML document and allows you to download it all as an SVG file.
JavaScript
840
star
14

ingredient-phrase-tagger

Extract structured data from ingredient phrases using conditional random fields
Python
784
star
15

Emphasis

Dynamic Deep-Linking and Highlighting
JavaScript
576
star
16

tamper

Ruby
499
star
17

three-loader-3dtiles

This is a Three.js loader module for handling OGC 3D Tiles, created by Cesium. It currently supports the two main formats, Batched 3D Model (b3dm) - based on glTF Point cloud.
TypeScript
444
star
18

react-prosemirror

A library for safely integrating ProseMirror and React.
TypeScript
418
star
19

rd-blender-docker

A collection of Docker containers for running Blender headless or distributed ✨
Python
415
star
20

Register

Android Library and App for testing Play Store billing
Kotlin
381
star
21

text-balancer

Eliminate typographic widows and other type crimes with this javascript module
JavaScript
373
star
22

document-viewer

The NYTimes Document Viewer
JavaScript
310
star
23

ios-360-videos

NYT360Video plays 360-degree video streamed from an AVPlayer on iOS.
Objective-C
273
star
24

three-story-controls

A three.js camera toolkit for creating interactive 3d stories
TypeScript
247
star
25

backbone.trackit

Manage unsaved changes in a Backbone Model.
JavaScript
202
star
26

aframe-loader-3dtiles-component

A-Frame component using 3D-Tiles
JavaScript
187
star
27

marvin

A go-kit HTTP server for the App Engine Standard Environment
Go
177
star
28

drone-gke

Drone plugin for deploying containers to Google Kubernetes Engine (GKE)
Go
165
star
29

Chronicler

A better way to write your release notes.
JavaScript
162
star
30

nginx-vod-module-docker

Docker image for nginx with Kaltura's VoD module used by The New York Times
Dockerfile
161
star
31

collectd-rabbitmq

A collected plugin, written in python, to collect statistics from RabbitMQ.
Python
143
star
32

public_api_specs

The API Specs (in OpenAPI/Swagger) for the APIs available from developer.nytimes.com
136
star
33

gunsales

Statistical analysis of monthly background checks of gun purchases
R
130
star
34

gcp-vault

A client for securely retrieving secrets from Vault in Google Cloud infrastructure
Go
119
star
35

rd-bundler-3d-plugins

Bundler plugins for optimizing glTF 3D models
JavaScript
119
star
36

Fech

Deprecated. Please see https://github.com/dwillis/Fech for a maintained fork.
Ruby
115
star
37

data-training

Files from the NYT data training program, available for public use.
114
star
38

drone-gae

Drone plugin for managing deployments and services on Google App Engine (GAE)
Go
97
star
39

mock-ec2-metadata

Go
95
star
40

encoding-wrapper

Collection of Go wrappers for Video encoding cloud providers (moved to @video-dev)
Go
85
star
41

redux-taxi

🚕 Component-driven asynchronous SSR in isomorphic Redux apps
JavaScript
70
star
42

video-captions-api

Agnostic API to generate captions for media assets across different transcription services.
Go
61
star
43

lifeline

A cron-based alternative to running daemons
Ruby
58
star
44

gcs-helper

Tool for proxying and mapping HTTP requests to Google Cloud Storage (GCS).
Go
54
star
45

logrotate

Go
54
star
46

httptest

A simple concurrent HTTP testing tool
Go
48
star
47

kyt-starter-universal

Deprecated, see: https://github.com/NYTimes/kyt/tree/master/packages/kyt-starter-universal
JavaScript
33
star
48

nytcampfin

A thin Python client for The New York Times Campaign Finance API
Python
27
star
49

safejson

safeJSON provides replacements for the 'load' and 'loads' methods in the standard Python 'json' module.
Python
27
star
50

thumbor-docker-image

Docker image for Thumbor smart imaging service
26
star
51

times_wire

A thin Ruby client for The New York Times Newswire API
Ruby
26
star
52

haiti-debt

Historical data on Haiti’s debt payments to France collected by The New York Times.
21
star
53

hhs-child-migrant-data

Data from the U.S. Department of Human Health and Services on children who have migrated to the United States without an adult.
21
star
54

jsonlogic

Clojure
20
star
55

elemental-live-client

JS library to communicate with Elemental live API.
JavaScript
19
star
56

Open-Source-Science-Fair

The New York Times Open Source Science Fair
JavaScript
19
star
57

tweetftp

Ruby Implementation of the Tweet File Transfer Protocol (APRIL FOOLS JOKE)
Ruby
19
star
58

prosemirror-change-tracking-prototype

JavaScript
18
star
59

plumbook

Data from the Plum Book, published by the GPO every 4 years
17
star
60

libvmod-queryfilter

Simple querystring filter/sort module for Varnish Cache v3-v6
M4
16
star
61

sneeze

Python
16
star
62

querqy-clj

Search Query Rewriting for Elasticsearch and more! Built on Querqy.
Clojure
14
star
63

sqliface

handy interfaces and test implementations for Go's database/sql package
Go
14
star
64

grocery

The grocery package provides easy mechanisms for storing, loading, and updating Go structs in Redis.
Go
13
star
65

oak-byo-react-prosemirror-redux

JavaScript
13
star
66

vase.elasticsearch

Vase Bindings for Elasticsearch
Clojure
11
star
67

library-customization-example

An example repo that customizes Library behavior
SCSS
11
star
68

counter

count things, either as a one-off or aggregated over time
Ruby
11
star
69

kyt-starter

The default starter-kyt for kyt apps.
JavaScript
10
star
70

tulsa-1921-data

Data files associated with our story on the 1921 race massacre in Tulsa, Oklahoma.
10
star
71

open-blog-projects

A repository for code examples that are paired with our Open Blog posts
Swift
9
star
72

rd-mobile-pg-demos

HTML
9
star
73

pocket_change

Python
9
star
74

mentorship

7
star
75

sort_by_str

SQL-like sorts on your Enumerables
Ruby
7
star
76

drone-gdm

Drone.io plugin to facilitate the use of Google Deployment Manager in drone deploy phase.
Go
6
star
77

kyt-starter-static

Deprecated, see: https://github.com/NYTimes/kyt/tree/master/packages/kyt-starter-static
JavaScript
6
star
78

s3yum

Python
5
star
79

pocket

Python
5
star
80

drone-openapi

A Drone plugin for publishing Open API service specifications
Go
5
star
81

threeplay

Go client for the 3Play API.
Go
4
star
82

amara

Amara client for Go
Go
4
star
83

go-compare-expressions

Go
3
star
84

kaichu

Python
3
star
85

license

NYT Apache 2.0 license
3
star
86

prosemirror-tooltip

JavaScript
2
star
87

photon-dev_demo

A "Sustainable Systems, Powered By Python" Demo Repository (1 of 3)
Shell
2
star
88

std-cat

Content Aggregation Technology — a standard for content aggregation on the Web
HTML
1
star