Objective-C 代码规范 (译)

2018-02-08  本文已影响44人  桑夏君

Preface

Version: 0.9.0
Our general coding conventions at Spotify are documented on an internal wiki, but specifics for Objective-C and Objective-C++ code in the iOS client are documented here.

Spotify通用的代码规范公约在内部的wiki上,但是特定于Objective-C和Objective-C++的iOS客户端代码规范刊发于此。

License

Copyright (c) 2015-2016 Spotify AB.
This work is licensed under a Creative Commons Attribution 4.0 International License.


Table of Contents (目录)

  1. Spacing, Lines and Formatting (空格,行和格式化)
  2. Brackets (括号)
  3. Naming (命名)
  4. Comments (注释))
  5. Pragma Marks
  6. Constants (常量)
  7. Return Early (Return Early原则)
  8. Initializers (初始化)
  9. Headers
  10. Nullability
  11. Strings (字符串)
  12. Dot Notation (点语法)
  13. Categories (类目)

Spacing, Lines and Formatting (空格,行和格式化)

Line length (行的长度)

Whitespace (空格)

Example:

foo("bar") 

Not:

foo( "bar" )

Containers (容器)

NSArray *array = @[@"uno", @"dos", @"tres", @"cuatro"];
NSArray *array = @[
    @"This is how we do, yeah, chilling, laid back",
    @"Straight stuntin’ yeah we do it like that",
    @"This is how we do, do do do do, this is how we do",
];
NSDictionary *dict = @{@"key" : @"highway"};
NSDictionary *dict = @{
    @"key1" : @"highway",
    @"key2" : @"heart",
};

Brackets (括号)

if (itsMagic) {
    [self makeItEverlasting];
}
if (hasClue) {
    knowExactlyWhatToDo();
} else if (seeItAllSoClear) {
    writeItDown();
} else {
    sing();
    dance();
}

Naming (命名规则)


Comments (注释)

Example:

/*
 This is a multi-line comment. The opening and closing markers are on their
 own lines.

 This is a new paragraph in the same block comment.
 */

stop(); // Hammer-time!

// this is a very brief comment.

Pragma Marks


Constants (常量)

extern NSString * const SPTCodeStandardErrorDomain;

Return Early (Return Early原则)

Example:

- (void)setFireToTheRain:(id)rain
{
    if ([_rain isEqualTo:rain]) {
        return;
    }

    _rain = rain;
}

Initializers (初始化)

Example:

- (instancetype)init 
{
    self = [super init];
 
    if (self) {
        // initialize instance variables here
    }
 
    return self;
}

Headers


Nullability

#import <Foundation/Foundation.h>

@protocol SPTPlaylist;

NS_ASSUME_NONNULL_BEGIN

typedef void(^SPTSomeBlock)(NSData * _Nullable data, NSError * _Nullable error);

@interface SPTYourClass : NSObject

@property (nonatomic, copy, readonly, nullable) NSString *customTitle;
@property (nonatomic, strong, readonly) id<SPTPlaylist> playlist;

- (nullable instancetype)initWithPlaylist:(id<SPTPlaylist>)playlist
                              customTitle:(nullable NSString *)customTitle;

@end

NS_ASSUME_NONNULL_END

Strings (字符串)


Dot Notation (点语法)

[self doSomething];
[MyClass sharedInstance];
self.myString = @"A string";
_myString = nil;

Categories (类目)

上一篇 下一篇

猜你喜欢

热点阅读