Objective-C编程风格指南

一篇oc编码风格的文章,有什么不对的地方请指出

引见

下面是来自苹果的一些有关编码风格指导的文件。如果在本文没有提到的内容,在这些文件中可能可以查到:

点语法

建议用点语法表示,并设置属性

For example:

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

Not:

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

空格

流程控制(if/else/switch/while),新的分支应该从新的一行开始

For example:

if (user.isHappy) {
    // Do something
}
else {
    // Do something else
}

For example:

if (!error) {
    return success;
}

Not:

if (!error)
    return success;

or

if (!error) return success;

三元运算符

三元运算符的意图是为了增加代码的简洁,三元运算符应该仅用一个表达式来执行一个条件判断,多个条件更多的是用if语句来执行。

For example:

result = a > b ? x : y;

Not:

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

方法

定义一个方法,应该在- or +后面加一个空格,多个参数应该用空格分开。

For example:

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

变量命名

变量命名应该具有描述性意义,一个变量的名字需要有正确的使用价值。
不推荐使用单一的字母变量名,除了循环中的计数器变量。
在任何可能的情况下,应该使用属性定义代替成员变量。

For example:

@interface NYTSection: NSObject

@property (nonatomic) NSString *headline;

@end

Not:

@interface NYTSection : NSObject {
    NSString *headline;
}

变量修饰符

当涉及到变量修饰符introduced with ARC,修饰符the qualifier (__strong, __weak, __unsafe_unretained, __autoreleasing)应该写在 * 和变量名之间,例如:NSString * __weak text

一般命名

苹果的命名规则在任何可能的地方都试用, 包括内存管理规则 http://stackoverflow.com/a/2865194/340508.
尽量用长的、描述性强的、有价值的名字总是好的。

For example:

UIButton *settingsButton;

Not

UIButton *setBut;

定义类名和常量的时候,需要添加3个字母的标识符,不要用两个字母。并遵循驼峰命名规则。两个字母的前缀是苹果所保留的命名reserved for use by Apple.

For example:

static const NSTimeInterval NYTArticleViewControllerNavigationFadeAnimationDuration = 0.3;

Not:

static const NSTimeInterval fadetime = 1.7;

属性和局部变量必须以小写字母开头

类别

类别为一个类提供功能的类,类别的命名应该具有实际意义。

For example:

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

Not:

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

注释

代码中添加相应的注释对代码的维护有很大的帮助。不推荐成块的注释,因为代码应该尽可能的自我记录,只需要间接性的,很少的注释。

不可变对象

NSString, NSDictionary, NSArray, 和 NSNumber的创建应该使用简单的方式。

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

当访问一个CGRect中的 x, y, width, or height这些成员时,必须使用CGGeometry functions 来替代直接访问成员. 从苹果的 CGGeometry 参考文档来看:

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;

常量

常量尽量用static声明,有时也可以用#define宏定义声明。

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

枚举类型

枚举一般使用固定的格式创建,苹果推荐使用NS_ENUM来创建。

Example:

typedef NS_ENUM(NSInteger, NYTAdRequestState) {
    NYTAdRequestStateInactive,
    NYTAdRequestStateLoading
};

位掩码

当使用bitmasks时,必须使用NS_OPTIONS宏创建。

Example:

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

私有属性

私有属性应该在类的实现文件implementation中声明,就是在类扩展中声明。
For example:

@interface NYTAdvertisement ()

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

@end
@implementation NYTAdvertisement

单例

单例对象应该使用线程安全的方式来创建。

+ (instancetype)sharedInstance {
    static id sharedInstance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[[self class] alloc] init];
    });

    return sharedInstance;
}

这将防止 可能意想不到的crashes.

Imports

在同时导入多个类的时候必须使用分组的方式来区分http://ashfurrow.com/blog/structuring-modern-objective-c.

框架导入使用@import

// Frameworks
@import QuartzCore;

// Models
#import "NYTUser.h"

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

协议

定义协议方法的第一个参数应该是一个该类的对象,delegate or data source protocol
这样有助于消除同时被多个对象引用的协议所带来的歧义。

For example:

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

Not:

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

其他的Objective-C代码风格

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,308评论 19 139
  • 从其他地方整理了一些编码规范的资料,分享给大家。YoY 1.语言(Language) 需要使用US English...
    大脸猫121阅读 3,173评论 0 2
  • 引言 一直以来都是在谈如何开发, 如开发的小技巧小经验 今天为什么突然说起编程规范来了呢? 因为在我看来, 编程规...
    诺之林阅读 3,555评论 1 5
  • Introduction 这个style guide规范描述了我们iOS开发团队喜欢的Objectiv-C编程习惯...
    小山Sam阅读 3,870评论 0 4
  • 本文转自:Objective-C 编码风格指南 | www.samirchen.com 背景 保证自己的代码遵循团...
    SamirChen阅读 3,471评论 1 3