简单-项目开发步骤之代码规范

1.建议用.符号代替括号用于设置或获取属性值

For example:

view.backgroundColor = [UIColororangeColor];[UIApplicationsharedApplication].delegate;

Not:

[viewsetBackgroundColor:[UIColororangeColor]];

UIApplication.sharedApplication.delegate;

2.空格

a.缩进必须使用4个空格。没有缩进和制表符。

b.一定要在Xcode中设置此首选项。方法括号和其他括号(如果/其他/开关/等等)。必须打开在同一行语句。括号必须关闭在一个新行。

For example:

if(user.isHappy) {

// Do something

}

else{

// Do something else

}

3.条件语句:必须有括号

For example:

if(!error) {returnsuccess;}

Not:

if(!error)returnsuccess;

or

if(!error)returnsuccess;

4.三元运算符:三元操作符的意图,?,是增加清晰或代码整洁。三元应该只评估每一个条件表达式。评估多个条件通常是更容易理解作为一个if语句或重构命名变量。

For example:

result = a > b ? x : y;

Not:

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

5.错误处理:当方法返回一个错误参数通过引用,代码必须打开返回值,不得打开错误变量。

For example:

NSError*error;if(![selftrySomethingWithError:&error]) {// Handle Error}

Not:

NSError*error;[selftrySomethingWithError:&error];if(error) {// Handle Error}

6.方法

For example:

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

7.变量:见名知意

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.AttributedStringhints 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: SimplylastModifiedcan be ambiguous; depending on context, one could reasonably assume it is one of a few different types.

NSURL *URLvs.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 *textnotNSString* textorNSString * text, except in the case of constants (NSString * const NYTConstantString).

For example:

interfaceNYTSection:NSObject@property(nonatomic)NSString*headline;@end

Not:

@interfaceNYTSection:NSObject{NSString*headline;}

8.变量限定符:

For example:

NSString * __weak text.

9.命名:描述性的方法和变量名越清楚越好

For example:

UIButton *settingsButton;

Not

UIButton *setBut;

For example:

staticconstNSTimeIntervalNYTArticleViewControllerNavigationFadeAnimationDuration =0.3;

Not:

staticconstNSTimeIntervalfadetime =1.7;

For example:

@synthesize descriptiveVariableName = _descriptiveVariableName;

Not:

idvarnm;

10.分类

类别建议简明地细分功能,用来描述该功能

For example:

@interfaceUIViewController(NYTMediaPlaying)@interfaceNSString(NSStringEncodingDetection)

Not:

@interfaceNYTAdvertisement(private)

@interfaceNSString(NYTAdditions)

For example:

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

Not:

@interfaceNSArray(NYTAccessors)

- (id)objectOrNilAtIndex:(NSUInteger)index;

@end

11.注释

When they are needed, comments SHOULD be used to explainwhya 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.

12.init and dealloc

dealloc方法应放置在顶部的实现,直接放在@ synthesize和@dynamic语句之后。init方法应该直接放置在dealloc任何类的方法。

- (instancetype)init {

self = [superinit];// or call the designated initializer

if(self) {

// Custom initialization

}

returnself;

}

12.文字

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 = [NSArrayarrayWithObjects:@"Brian",@"Matt",@"Chris",@"Alex",@"Steve",@"Paul",nil];

NSDictionary*productManagers = [NSDictionarydictionaryWithObjectsAndKeys:@"Kate",@"iPhone",@"Kamal",@"iPad",@"Bill",@"Mobile Web",nil];

NSNumber*shouldUseLiterals = [NSNumbernumberWithBool:YES];

NSNumber*buildingZIPCode = [NSNumbernumberWithInteger:10018];

13.CGRECT

For example:

CGRectframe = self.view.frame;CGFloatx = CGRectGetMinX(frame);CGFloaty = CGRectGetMinY(frame);CGFloatwidth = CGRectGetWidth(frame);CGFloatheight = CGRectGetHeight(frame);

Not:

CGRectframe = self.view.frame;

CGFloatx = frame.origin.x;

CGFloaty = frame.origin.y;

CGFloatwidth = frame.size.width;

CGFloatheight = frame.size.height;

14.常量

For example:

staticNSString*constNYTAboutViewControllerCompanyName =@"The New York Times Company";staticconstCGFloatNYTImageThumbnailHeight =50.0;

Not:

#defineCompanyName@"The New York Times Company"

#definethumbnailHeight2

15.枚举

Example:

typedefNS_ENUM(NSInteger, NYTAdRequestState) {

NYTAdRequestStateInactive,

NYTAdRequestStateLoading

};

16.在处理位掩码时,必须使用NS_OPTIONS宏。

Example:

typedefNS_OPTIONS(NSUInteger, NYTAdCategory) {

NYTAdCategoryAutos      =1<<0,

NYTAdCategoryJobs       =1<<1,

NYTAdCategoryRealState  =1<<2,

NYTAdCategoryTechnology =1<<3

};

17.私有方法:

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

For example:

@interfaceNYTAdvertisement()

@property(nonatomic,strong) GADBannerView *googleAdView;

@property(nonatomic,strong) ADBannerView *iAdView;

@property(nonatomic,strong) UIWebView *adXWebView;

@end

18.图片名称

图片应该命名为一个驼峰式大小写字符串的描述他们的目的,其次是无前缀的名称他们定制的类或属性(如果有的话),其次是进一步描述颜色和/或位置,最后他们的状态。

For example:

RefreshBarButtonItem/RefreshBarButtonItem@2xandRefreshBarButtonItemSelected/RefreshBarButtonItemSelected@2x

ArticleNavigationBarWhite/ArticleNavigationBarWhite@2xandArticleNavigationBarBlackSelected/ArticleNavigationBarBlackSelected@2x.

18.boolen

Values MUST NOT be compared directly toYES, becauseYESis defined as1, and aBOOLin Objective-C is aCHARtype that is 8 bits long (so a value of11111110will returnNOif compared toYES).

For an object pointer:

if(!someObject) {}if(someObject ==nil) {}

For aBOOLvalue:

if(isAwesome)if(!someNumber.boolValue)if(someNumber.boolValue ==NO)

Not:

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

@property (assign, getter=isEditable)BOOLeditable;

20.单例

Singleton objects SHOULD use a thread-safe pattern for creating their shared instance.

+ (instancetype)sharedInstance {

staticidsharedInstance =nil;

staticdispatch_once_tonceToken;

dispatch_once(&onceToken, ^{

sharedInstance = [[[selfclass]alloc]init];

});

returnsharedInstance;

}

21.imports

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

Note: For modules use the@importsyntax.

// Frameworks

@import QuartzCore;

// Models

#import"NYTUser.h"

// Views

#import"NYTButton.h"

#import"NYTUserView.h"

22.协议

In adelegate 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;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容