Giter Site home page Giter Site logo

objective-c-style-guide's Introduction

The official raywenderlich.com Objective-C style guide.

This style guide outlines the coding conventions for raywenderlich.com.

Introduction

The reason we made this style guide was so that we could keep the code in our books, tutorials, and starter kits nice and consistent - even though we have many different authors working on the books.

This style guide is different from other Objective-C style guides you may see, because the focus is centered on readability for print and the web. Many of the decisions were made with an eye toward conserving space for print, easy legibility, and tutorial writing.

Credits

The creation of this style guide was a collaborative effort from various raywenderlich.com team members under the direction of Nicholas Waynik. The team includes: Soheil Moayedi Azarpour, Ricardo Rendon Cepeda, Tony Dahbura, Colin Eberhardt, Matt Galloway, Greg Heo, Matthijs Hollemans, Christopher LaPollo, Saul Mora, Andy Pereira, Mic Pringle, Pietro Rea, Cesare Rocchi, Marin Todorov, Nicholas Waynik, and Ray Wenderlich

We would like to thank the creators of the New York Times and Robots & Pencils' Objective-C Style Guides. These two style guides provided a solid starting point for this guide to be created and based upon.

Background

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

Language

US English should be used.

Preferred:

UIColor *myColor = [UIColor whiteColor];

Not Preferred:

UIColor *myColour = [UIColor whiteColor];

Code Organization

Use #pragma mark - to categorize methods in functional groupings and protocol/delegate implementations following this general structure.

#pragma mark - Lifecycle

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

#pragma mark - Custom Accessors

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

#pragma mark - IBActions

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

#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 - NSCopying

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

#pragma mark - NSObject

- (NSString *)description {}

Spacing

  • Indent using 2 spaces (this conserves space in print and makes line wrapping less likely). 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
}

Not 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 separate functionality, but often there should probably be new methods.
  • Prefer using auto-synthesis. But if necessary, @synthesize and @dynamic should each be declared on new lines in the implementation.
  • Colon-aligning method invocation should often be avoided. There are cases where a method signature may have >= 3 colons and colon-aligning makes the code more readable. Please do NOT however colon align methods containing blocks because Xcode's indenting makes it illegible.

Preferred:

// blocks are easily readable
[UIView animateWithDuration:1.0 animations:^{
  // something
} completion:^(BOOL finished) {
  // something
}];

Not Preferred:

// colon-aligning makes the block indentation hard to read
[UIView animateWithDuration:1.0
                 animations:^{
                     // something
                 }
                 completion:^(BOOL finished) {
                     // something
                 }];

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. Exception: This does not apply to those comments used to generate documentation.

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 Preferred:

UIButton *setBut;

A three letter prefix should always be used for class names and constants, however may be omitted for Core Data entity names. For any official raywenderlich.com books, starter kits, or tutorials, the prefix 'RWT' should be used.

Constants should be camel-case with all words capitalized and prefixed by the related class name for clarity.

Preferred:

static NSTimeInterval const RWTTutorialViewControllerNavigationFadeAnimationDuration = 0.3;

Not Preferred:

static NSTimeInterval const fadetime = 1.7;

Properties should be camel-case with the leading word being lowercase. Use auto-synthesis for properties rather than manual @synthesize statements unless you have good reason.

Preferred:

@property (strong, nonatomic) NSString *descriptiveVariableName;

Not Preferred:

id varnm;

Underscores

When using properties, instance variables should always be accessed and mutated using self.. This means that all properties will be visually distinct, as they will all be prefaced with self..

An exception to this: inside initializers, the backing instance variable (i.e. _variableName) should be used directly to avoid any potential side effects of the getters/setters.

Local variables should not contain underscores.

Methods

In method signatures, there should be a space after the method type (-/+ symbol). There should be a space between the method segments (matching Apple's style). Always include a keyword and be descriptive with the word before the argument which describes the argument.

The usage of the word "and" is reserved. It should not be used for multiple parameters as illustrated in the initWithWidth:height: example below.

Preferred:

- (void)setExampleText:(NSString *)text image:(UIImage *)image;
- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;
- (id)viewWithTag:(NSInteger)tag;
- (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height;

Not Preferred:

-(void)setT:(NSString *)text i:(UIImage *)image;
- (void)sendAction:(SEL)aSelector :(id)anObject :(BOOL)flag;
- (id)taggedView:(NSInteger)tag;
- (instancetype)initWithWidth:(CGFloat)width andHeight:(CGFloat)height;
- (instancetype)initWith:(int)width and:(int)height;  // Never do this.

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.

Private properties should be used in place of instance variables whenever possible. Although using instance variables is a valid way of doing things, by agreeing to prefer properties our code will be more consistent.

Direct access to instance variables that 'back' properties 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.

Preferred:

@interface RWTTutorial : NSObject

@property (strong, nonatomic) NSString *tutorialName;

@end

Not Preferred:

@interface RWTTutorial : NSObject {
  NSString *tutorialName;
}

Property Attributes

Property attributes should be explicitly listed, and will help new programmers when reading the code. The order of properties should be storage then atomicity, which is consistent with automatically generated code when connecting UI elements from Interface Builder.

Preferred:

@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (strong, nonatomic) NSString *tutorialName;

Not Preferred:

@property (nonatomic, weak) IBOutlet UIView *containerView;
@property (nonatomic) NSString *tutorialName;

Properties with mutable counterparts (e.g. NSString) should prefer copy instead of strong. Why? Even if you declared a property as NSString somebody might pass in an instance of an NSMutableString and then change it without you noticing that.

Preferred:

@property (copy, nonatomic) NSString *tutorialName;

Not Preferred:

@property (strong, nonatomic) NSString *tutorialName;

Dot-Notation Syntax

Dot syntax is purely a convenient wrapper around accessor method calls. When you use dot syntax, the property is still accessed or changed using getter and setter methods. Read more here

Dot-notation should always be used for accessing and mutating properties, as it makes code more concise. Bracket notation is preferred in all other instances.

Preferred:

NSInteger arrayCount = [self.array count];
view.backgroundColor = [UIColor orangeColor];
[UIApplication sharedApplication].delegate;

Not Preferred:

NSInteger arrayCount = self.array.count;
[view setBackgroundColor:[UIColor orangeColor]];
UIApplication.sharedApplication.delegate;

Literals

NSString, NSDictionary, NSArray, and NSNumber literals should be used whenever creating immutable instances of those objects. Pay special care that nil values can 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 *buildingStreetNumber = @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 *buildingStreetNumber = [NSNumber numberWithInteger:10018];

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 RWTAboutViewControllerCompanyName = @"RayWenderlich.com";

static CGFloat const RWTImageThumbnailHeight = 50.0;

Not Preferred:

#define CompanyName @"RayWenderlich.com"

#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()

For Example:

typedef NS_ENUM(NSInteger, RWTLeftMenuTopItemType) {
  RWTLeftMenuTopItemMain,
  RWTLeftMenuTopItemShows,
  RWTLeftMenuTopItemSchedule
};

You can also make explicit value assignments (showing older k-style constant definition):

typedef NS_ENUM(NSInteger, RWTGlobalConstants) {
  RWTPinSizeMin = 1,
  RWTPinSizeMax = 5,
  RWTPinCountMin = 100,
  RWTPinCountMax = 500,
};

Older k-style constant definitions should be avoided unless writing CoreFoundation C code (unlikely).

Not Preferred:

enum GlobalConstants {
  kMaxPinSize = 5,
  kMaxPinCount = 500,
};

Case Statements

Braces are not required for case statements, unless enforced by the complier.
When a case contains more than one line, braces should be added.

switch (condition) {
  case 1:
    // ...
    break;
  case 2: {
    // ...
    // Multi-line example using braces
    break;
  }
  case 3:
    // ...
    break;
  default: 
    // ...
    break;
}

There are times when the same code can be used for multiple cases, and a fall-through should be used. A fall-through is the removal of the 'break' statement for a case thus allowing the flow of execution to pass to the next case value. A fall-through should be commented for coding clarity.

switch (condition) {
  case 1:
    // ** fall-through! **
  case 2:
    // code executed for values 1 and 2
    break;
  default: 
    // ...
    break;
}

When using an enumerated type for a switch, 'default' is not needed. For example:

RWTLeftMenuTopItemType menuType = RWTLeftMenuTopItemMain;

switch (menuType) {
  case RWTLeftMenuTopItemMain:
    // ...
    break;
  case RWTLeftMenuTopItemShows:
    // ...
    break;
  case RWTLeftMenuTopItemSchedule:
    // ...
    break;
}

Private Properties

Private properties should be declared in class extensions (anonymous categories) in the implementation file of a class. Named categories (such as RWTPrivate or private) should never be used unless extending another class. The Anonymous category can be shared/exposed for testing using the +Private.h file naming convention.

For Example:

@interface RWTDetailViewController ()

@property (strong, nonatomic) GADBannerView *googleAdView;
@property (strong, nonatomic) ADBannerView *iAdView;
@property (strong, nonatomic) UIWebView *adXWebView;

@end

Booleans

Objective-C uses YES and NO. Therefore true and false should only be used for CoreFoundation, C or C++ code. 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.

Preferred:

if (someObject) {}
if (![anotherObject boolValue]) {}

Not Preferred:

if (someObject == nil) {}
if ([anotherObject boolValue] == NO) {}
if (isAwesome == YES) {} // Never do this.
if (isAwesome == true) {} // Never do this.

If the name of a BOOL property is expressed as an adjective, the property can omit the “is” prefix but specifies the conventional name for the get accessor, for example:

@property (assign, getter=isEditable) BOOL editable;

Text and example taken from the Cocoa Naming Guidelines.

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;

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. In general, the best use of the ternary operator is during assignment of a variable and deciding which value to use.

Non-boolean variables should be compared against something, and parentheses are added for improved readability. If the variable being compared is a boolean type, then no parentheses are needed.

Preferred:

NSInteger value = 5;
result = (value != 0) ? x : y;

BOOL isHorizontal = YES;
result = isHorizontal ? x : y;

Not Preferred:

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

Init Methods

Init methods should follow the convention provided by Apple's generated code template. A return type of 'instancetype' should also be used instead of 'id'.

- (instancetype)init {
  self = [super init];
  if (self) {
    // ...
  }
  return self;
}

See Class Constructor Methods for link to article on instancetype.

Class Constructor Methods

Where class constructor methods are used, these should always return type of 'instancetype' and never 'id'. This ensures the compiler correctly infers the result type.

@interface Airplane
+ (instancetype)airplaneWithType:(RWTAirplaneType)type;
@end

More information on instancetype can be found on NSHipster.com.

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);
CGRect frame = CGRectMake(0.0, 0.0, width, height);

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;
CGRect frame = (CGRect){ .origin = CGPointZero, .size = frame.size };

Golden Path

When coding with conditionals, the left hand margin of the code should be the "golden" or "happy" path. That is, don't nest if statements. Multiple return statements are OK.

Preferred:

- (void)someMethod {
  if (![someOther boolValue]) {
	return;
  }

  //Do something important
}

Not Preferred:

- (void)someMethod {
  if ([someOther boolValue]) {
    //Do something important
  }
}

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

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

This will prevent possible and sometimes prolific crashes.

Line Breaks

Line breaks are an important topic since this style guide is focused for print and online readability.

For example:

self.productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];

A long line of code like this should be carried on to the second line adhering to this style guide's Spacing section (two spaces).

self.productsRequest = [[SKProductsRequest alloc] 
  initWithProductIdentifiers:productIdentifiers];

Smiley Face

Smiley faces are a very prominent style feature of the raywenderlich.com site! It is very important to have the correct smile signifying the immense amount of happiness and excitement for the coding topic. The end square bracket is used because it represents the largest smile able to be captured using ascii art. A half-hearted smile is represented if an end parenthesis is used, and thus not preferred.

Preferred:

:]

Not Preferred:

:)

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:

objective-c-style-guide's People

Contributors

chrisgrant avatar colineberhardt avatar cwagdev avatar funkyboy avatar gregheo avatar hollance avatar icanzilb avatar mattglover avatar ndubbs avatar rwenderlich avatar tdahbura avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

objective-c-style-guide's Issues

Language (i.e. US English)

I couldn't find any mention of what language we should use. I know it's slightly pedantic, but I think it should be explicit that methods, variable names etc use a standard choice of language. Presumably we'd pick US English.

It only really matters in things like color vs colour, recogniser vs recognizer, etc.

Thoughts?

1 liner if statements contradicts Golden Path

@ndubbs

In Conditionals the guide says:

Not preferred:
if (!error) return success;

In Golden Path the guide says:

Preferred:
if (![someOther boolValue]) return;

These look essentially the same to me, I think in this case we are contradicting ourselves.

English should be used, really?

I get the point on using (a particular sort of) English. Of course on a guide something must be agreed, but I want to point out that using English is a big a source of problems. This is because Apple uses it. Try to add an instance variable named _alpha to an UIView subclass and you will see. Crashes and odd things are guaranteed to happen without any previous warning. I avoid English in my code for that reason but other than using a different language, is there a consistent way to prevent this kind of issue?. What do English coders to prevent it? a custom prefix or suffix on each instance var?

What is the recommended line width for Objective-C?

So this was the primary question which I was trying to answer when I found this guide. Strangely enough, neither in Apple's official documentation nor here it is not indicated. Google, on the other hand, in its style guide recommends 100 columns. Objective-C is quite a verbose language, so may be even 120 is still good.

Remove Image Naming section

I think the guidelines in this section to beyond the scope of what we're trying to do with this style guide and is overly onerous. I propose we remove the entire section.

What do you all think?

Be explicit about the datatype when comparing

I have this open as a pull request but it's a bit hidden, so I'm opening up a new issue for this as well.

In the guide it currently says this is how you check for nil:

if (someObject) ...
if (!someObject)...

I strongly suggest we are always explicit about this sort of thing:

if (someObject != nil) ...
if (someObject == nil)...

That makes it immediately clear what you're comparing.

I'd like the syntax if (a) and if (!a) to be limited to booleans only.

So not this either:

if (someInt) { ... }

The only exception I make for this in my own code is init methods:

if ((self = [super init]))

because that is idiomatic.

Switch statement

How to format a switch statement?

How to point out that a case falls through?

Good vs bad

I don't like the labels Good and Bad. That gives these choices a value judgment while they are not. Most of these choices -- such as where you put the braces -- are simply that: choices.

With people getting emotional over coding style guides, using labels such as Good and Bad isn't helping any.

RWT prefix typo in constant definition

In the preffered box you show:
static NSTimeInterval const RWTutorialViewControllerNavigationFadeAnimationDuration = 0.3;

where you previously state to use 3 letter RWT prefix, so it should be:
RWTTutorial(...)

Error handling

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

Hello,

Do you have some examples of Apple API that do that ? That fill the NSError in success cases ?

Init methods

How does everyone write their init methods?

I use:

- (id)init
{
  if ((self = [super init])) {
    . . .
  }
  return self;
}

The variations on this are endless. Apple seems to prefer this now:

- (id)init
{
  self = [super init];
  if (self) {
    . . .
  }
  return self;
}

But I also see people do this:

- (id)init
{
  self = [super init];
  if (self == nil) return nil;

  return self;
}

I like the first one because it just looks aesthetically pleasing to me.

Should we indent with 2 spaces?

I know that 4-space is generally more popular than 2-space, however, I think this code style should reflect the fact that the code we are writing will be reproduced in blog posts, tutorials and books where there are significant restrictions on page-width.

When writing iOS 7 by tutorials there were significant wrapping issues (due in part to Apple's verbose naming conventions!).

I would like to propose the use of 2-space indentation in order to reduce the need to wrap lines when reproducing code within articles.

I want make new branch for Korean ver.

Hello I'm canapio. iOS developer.
This is very useful for me!
I'm Korean, and I want pull request Korean ver. (Not make yet)
If contributor permits this, I will pull request after make new localization folder and localized "objective-c-style-guide".
Thank you :-)

Should we use the 'f' suffix for float constants?

The current style guide does not detail whether we should or should not, but the 'f' suffix is lacking in one of the examples.

static const CGFloat RWImageThumbnailHeight = 50.0;

I am on the fence about this one.

关于枚举(Enumerated Types)的想法

枚举的想法,关于两种枚举的写法
个人建议,还是采用文中提到的旧方法
建议理由:
1.旧方法简单快捷,而且在不特定设置快捷代码块的情况下,系统自带,一般情况,敲出来enum就会提示
typedef enum : NSUInteger {
<#MyEnumValueA#>,
<#MyEnumValueB#>,
<#MyEnumValueC#>,
} <#MyEnum#>;

2.在OC与Swift混编的情况下,新的枚举不能使用,应为目前涉及到#define

在快捷和混编的情况下,我更倾向于枚举的旧写法

Symbol prefix: 2 vs. 3 characters

The Cocoa Guidelines are ambiguous when it comes to symbol prefixes. For example, the Coding Guidelines for Cocoa say (emphasis mine):

A prefix has a prescribed format. It consists of two or three uppercase letters and does not use underscores or “sub prefixes.”

However, the Programming with Objective-C: Conventions page states

Your own classes should use three letter prefixes. These might relate to a combination of your company name and your app name, or even a specific component within your app. As an example, if your company were called Whispering Oak, and you were developing a game called Zebra Surprise, you might choose WZS or WOZ as your class prefix.

What are your thoughts on this? I know the guide says to use RW, but since the three-letter prefix appears to be preferred, that wouldn't follow the convention. I know it's nitpicky, but that's what we're here for, right? :]

How do I indent something like this???

I just started writing objective c recently. This indentation is crazy.

How do I deal with something like this?

Note that this "alert" variable is already nested under 3 levels. So xocd automatically tries to wrap text if too long.

Where do i start a new line? where should the message:@"" start?


                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Broadcast Invite"
                                                                               message:@"Do you want to join??."
                                                                        preferredStyle:UIAlertControllerStyleAlert];

Ternary operator

I suggest we write it as such:

result = (a > b) ? x : y;

In other words, place parentheses around the condition. There are two reasons for this:

  1. It is easier to read
  2. You don't have to worry about operator precedence.

Direct access to properties.

The guide states:

"Direct access to instance variables that 'back' properties 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"

Since ARC there is no longer a reason to do so. With ARC you can safely access instance variables without any issues and doing it is MUCH faster. The linked Apple doc that recommends using always property accessors is outdated. Notice that according to said document the main reason to use properties is to help on manual memory management. This is the main reason the document points to:

"Sometimes it might seem tedious or pedantic, but if you use accessor methods consistently, the chances of having problems with memory management decrease considerably. If you are using retain and release on instance variables throughout your code, you are almost certainly doing the wrong thing"

This is no longer the case. Not using instance variables is just a prejudice based on earlier assumptions. We should start using them normally in the private scope of a class, that's completely fine now.

Properties should still be used for external object access but as said there is no longer any justification for using them in the private scope of a class, including accessing instance variables of the class own properties.

Common tasks in tutorials

I don't know if this is the right place to discuss this.
If not let me know.

When writing a tutorial/chapter it is likely you need to provide instructions for common tasks like "link against framework x" or "create a mobile provisioning profile". These require a sequence of tasks that is repeated over and over in many tutorials.

I propose to have a section in the site that describes these common tasks, so that in the tutorial we can simply say "link against framework x and y (here are instructions if you don't know how to link against a framework)" and that's all.

What do you think?

How to name methods

I see a lot of people do this:

whateverWithWidth:andHeight:

It will be good to mention that it is better to do:

whateverWithWidth:height:

Usage of "and" is reserved for when more than one thing happens:

doSomething:andSomethingElse:

Warning flags

What are good warning flags to enable by default?

I prefer -Wall -Wextra -Wno-unused-parameter. It might be good to have these as suggested settings.

Xcode behavior regarding indenting block

Does anyone know how to make Xcode auto-indent blocks correctly?

What I mean is that, according to this guide and to what I think is a much cleaner and readable code, blocks should be indented like the following:

Preferred:

// blocks are easily readable
[UIView animateWithDuration:1.0 animations:^{
  // something
} completion:^(BOOL finished) {
  // something
}];

Not Preferred:

// colon-aligning makes the block indentation hard to read
[UIView animateWithDuration:1.0
                 animations:^{
                     // something
                 }
                 completion:^(BOOL finished) {
                     // something
                 }];

But Xcode keeps wrongly indenting the inside-block code every semi-colon I type!

Can we lint to enforce some of this style guide?

I just finished writing a tutorial when I noticed right near the end an issue with the starter project. Most annoying!

I am just thinking out loud here, I wonder how much of this style guide you can enforce using static analysis tools. I haven't tried any Objective-C linting tools yet, has anyone tried OCLint or similar?

By skimming through our rules, I think it should be possible to enforce around 70% using a linking tool. And if such a tool doesn't exist - it's time to build one!

IBAction methods naming and parameters

I didn't see any rule about IBAction methods in the guide.

I think there are 2 parts to this:

  1. How to name such methods - "didPressButtonA" or "buttonAPressed", or something else. I myself, always prefix IBAction methods with "action" and that liberates me of coming up with a proper verb, subject, etc. so I always go for
-(IBAction)actionButtonA 

so there's no binding to what exactly the method will do (because this also might change along the way), but it says exactly "the method that is the action of buttonA"

  1. I always add the "sender" parameter, but I end up using it in maybe less than 1% of the cases ... I'm not sure about it ... if you won't use the sender param to me it feels stylewise the same if you gonna have
-(IBAction)actionButtonA;

or

-(IBAction)actionButtonA:(id)sender;

opinions?

What's the point on using properties instead of instance variables?

On the guide you state "Private properties should be used in place of instance variables whenever possible. Although using instance variables is a valid way of doing things, by agreeing to prefer properties our code will be more consistent."

Property accessors are MUCH slower than instance variable access. So why do not allow direct declaration of variables for private use in a class?. What do you mean by "consistent"

Init section contradicts Golden path section

Golden path states we should avoid putting code in if statements when possible. But in the Init section it says we should do:

if (self) {
...
}

while if we follow the Golden Path section this code should be:

if (!self) return nil;
...

Not sure which section is better, but it's confusing to get contradicting directions

How to break long lines?

This is less relevant for the web, but important for book authors. I think it would be great to provide some guidance about how to break long lines of code over multiple lines.

Should we use compound literal syntax?

While tech editing i7t I realised we have an inconsistency with some people using compound literal syntax:

self.imageView.frame = (CGRect){ .origin = CGPointZero, .size = self.photo.size };

Should we use this less-often used, yet highly useful syntax? Or use the CGRectMake macro for simplicity / familiarity?

My gut feeling is that we should use this feature, but ensure that the code style guidelines are easily discovered by reader (i.e. linked to by every tutorial), and that we make one goal of the style guideline to be educating the reader.

Should we include a section for property attributes?

Three arguments FOR this inclusion:

1) Consistency

UI elements linked as IBOutlets from Interface Builder are automatically generated with this convention:

@property (weak, nonatomic) IBOutlet UIView *exampleViewOne;

Yet many times I've encountered instances where properties are declared like so:

@property (nonatomic, strong) UIView *exampleViewTwo;

I think we should standardize this pattern to:

@property (storage, atomicity) ...

2) Default values

In the current style guide there is already a conflicting style regarding properties.
In Variables:

@property (nonatomic) NSString *tutorialName;

In Private Properties:

@property (nonatomic, strong) GADBannerView *googleAdView;

strong is the default state, but this may not be clear to new programmers.

3) Lack of Official Documentation

Property attributes and their correct usage is one of the least documented topics in Objective-C. They are hard to grasp and are a very common question in our community. I think we'd be doing a massive service to everyone by dedicating a section to them in our Style Guide :]

http://stackoverflow.com/questions/588866/atomic-vs-nonatomic-properties

Use style guide principles in examples

This may be a bit nit picky, but I think it would be an improvement if the principles in the document would be used in other principles examples.

For example, it is recommended that any property that has a mutable subclass (like NSString*), be declared with attributes nonatomic and copy. However, in most (if not all) of the other examples on the page, NSString is declared with nonatomic and strong.

[array count] vs array.count

The style guide as written says that properties should be used with dot notation, which I think is a fine rule. However, many people write:

x = self.array.count

There's nothing particularly wrong with that, except that count is not declared as a property. It might be worth putting this specific example in the guide.

The Smiley Face Debate :]

This one is just for fun!

In my first tutorial series I had my smiley face emoticons changed from :) to :].
I did not think the editors would actually change that - Lolz.

They're a very prominent style feature of the RW site, so I think we should dedicate a tiny section to them :]

arrayCount should be named something else

Is it possible to change this line:
NSInteger arrayCount = [self.array count];

to either
NSInteger names = self.names.count, or NSInteger names = [self.names count]

This is because I've seen a lot of inexperienced developers use array when naming an array, even though they should name using as high level of abstraction as possible (i.e. instead of nameArray, they should use names). And I think your style guide has a big influence within the Objective-C community.

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.