一. 代码命名规则1> 统一要求
•前缀使用(如:项目名字首字母缩写);
•含义清楚,尽量做到不需要注释也能了解其作用,若做不到,就加注释;
•使用全称,不适用缩写;2> 类的命名
•大驼峰式命名:每个单词的首字母都采用大写字母(如:MFHomePageViewController)
•后缀要求
1.Model:使用Model/Info作后缀(如:MFMineModel);
2.View: 使用View做后缀(如: MFMineView);
3.ViewController: 使用Controller做后缀 (如: MFHomeController);
4.ViewModel: 使用ViewModel做后缀 (如: MFMineViewModel);
5.UITableCell:使用Cell做后缀(如: MFNewsCell);
6.Protocol: 使用Delegate或者DataSource作为后缀(如: UITableViewDelegate);
7.涉及重写某个控件:使用控件做后缀(如: MFTabBar、MFNavigationController);
8.UI控件依次类推;3> 私有变量
•小驼峰式命名:第一个单词以小写字母开始,后面的单词的首字母全部大写(如:firstName、lastName);
•私有变量放在 .m 文件中声明;4> property变量
•小驼峰式命名 (如:
/// 注释
@property (nonatomic, copy) NSString *userName; );
•禁止使用synthesize关键词;5> 宏命名 (选择一种)
•全部大写,单词间用 _ 分隔。[不带参数](如: #define THIS_IS_AN_MACRO @“THIS_IS_AN_MACRO” );
•以字母 k 开头,后面遵循大驼峰命名。[不带参数] (如:#define kWidth self.frame.size.width);
•小驼峰命名。[带参数] (如:
#define getImageUrl(url) [NSURL URLWithString:[NSString stringWithFormat:@“%@%@",kBaseUrl,url]]6> Enum
•Enum类型的命名与类的命名规则一致;
•Enum中枚举内容的命名需要以该Enum类型名称开头;
•当使用Enum时,推荐使用新的固定基本类型规格,因为它有更强的类型检查和代码补全。现在SDK有一个宏NS_ENUM()来帮助和鼓励你使用固定的基本类型(如下:);
1)直接定义(值从0开始,依次增加):
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
AFNetworkReachabilityStatusUnknown,
AFNetworkReachabilityStatusNotReachable,
AFNetworkReachabilityStatusReachableViaWWAN,
AFNetworkReachabilityStatusReachableViaWiFi
};
2)也可以显式地赋值
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
AFNetworkReachabilityStatusUnknown = -1,
AFNetworkReachabilityStatusNotReachable = 0,
AFNetworkReachabilityStatusReachableViaWWAN = 1,
AFNetworkReachabilityStatusReachableViaWiFi = 2
};
错误实例:
enum AFNetworkReachabilityStatus {
AFNetworkReachabilityStatusUnknown = 5,
AFNetworkReachabilityStatusNotReachable = 10,
AFNetworkReachabilityStatusReachableViaWWAN = 50,
AFNetworkReachabilityStatusReachableViaWiFi = 60
};7> Delegate命名
•类的实例必须为回调方法的参数之一, 如
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
•回调方法的参数只有类自己的情况,方法名要符合实际含义, 如:
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
•以类的名字开头(回调方法存在两个以上参数的情况)以表明此方法是属于哪个类的, 如:
- (UITableViewCell *)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
•使用did和will通知Delegate已经发生的变化或将要发生的变化, 如:
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
二、代码组织
1> 在函数分组和protocol/delegate实现中使用#pragma mark -来分类方法;
2> 属性特性:所有属性应显示列出来,有助于新手阅读代码;属性特性的顺序应该是storage、atomicity,与在Interface Builder连接UI元素时自动生成代码一致。
实例:
@property (weak, nonatomic) IBOutlet UIView *containerView;
错误实例:
@property (nonatomic, weak) IBOutlet UIView *containerView;
注意:NSString应该使用copy 而不是 strong的属性特性。因为:即使你声明一个NSString的属性,有人可能传入一个NSMutableString的实例,然后在你没有注意的情况下修改它;
3> 点符号语法:点语法是一种很方便封装访问方法调用的方式。当你使用点语法时,通过使用getter或setter方法,属性仍然被访问或修改;点语法应该总是被用来访问和修改属性,因为它使代码更加简洁。[]符号更偏向于用在其他例子;
实例:
NSInteger arrayCount = self.array.count;
view.backgroundColor = [UIColor orangeColor];
[UIApplication sharedApplication].delegate;
错误实例:
NSInteger arrayCount = [self.array count];
[view setBackgroundColor:[UIColor orangeColor]];
[[UIApplication sharedApplication] delegate];
4> 常量:常量是容易重复被使用和无需通过查找和代替就能快速修改值。常量应该使用static来声明而不是使用#define,除非显式地使用宏(全局共用宏除外);
实例:
static NSString * const RWTAboutViewControllerCompanyName = @"RayWenderlich.com";
static CGFloat const RWTImageThumbnailHeight = 50.0;
错误实例:
#define CompanyName @"RayWenderlich.com"
#define thumbnailHeight 2
5> 布尔值:OC使用YES和NO。因为true和false应该只在CoreFoundation,C或C++代码使用。既然nil解析成NO,所以没有必要在条件语句比较。不要拿某样东西直接与YES比较,因为YES被定义为1和一个BOOL能被设置为8位;(为了在不同文件保持一致性和在视觉上更加简洁而考虑):
实例:
if (someObject) {}
if (![anotherObject boolValue]) {}
错误实例:
if (someObject == nil) {}
if ([anotherObject boolValue] == NO) {}
if (isAwesome == YES) {} // Never do this.
if (isAwesome == true) {} // Never do this.
6> 三元操作符:当需要提高代码的清晰性和简洁性时,三元操作符?:才会使用;单个条件求值常常需要它;多个条件求值时,如果使用if语句或重构成实例变量时,代码会更加易读;Non-boolean的变量与某东西比较,加上括号()会提高可读性;若被比较的变量是boolean类型,那么就不需要括号;
实例:
NSInteger value = 5;
result = (value != 0) ? x : y;
BOOL isHorizontal = YES;
result = isHorizontal ? x : y;
错误实例:
result = a > b ? x = c > d ? c : d : y;
7> init方法:Init方法应该遵循Apple生成代码模板的命名规则。返回类型应该使用instancetype而不是id;
实例:
- (instancetype)init {
self = [super init];
if (self) {
// ...
}
return self;
}
8> 类构造方法:当类构造方法被使用时,它应该返回类型是instancetype而不是id。这样确保编译器正确地推断结果类型(如下:);
@interface Airplane
+ (instancetype)airplaneWithType:(RWTAirplaneType)type;
@end
9> CGRect函数:当访问CGRect里的x,y,width, 或height时,应该使用CGGeometry函数而不是直接通过结构体来访问:
实例:
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);
错误实例:
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 };
10> 错误处理:当方法通过引用来返回一个错误参数,判断返回值而不是错误变量(在成功的情况下,有些Apple的APIs记录垃圾值(garbage values)到错误参数(如果non-NULL),那么判断错误值会导致false负值和crash):
实例:
NSError *error;
if (![self trySomethingWithError:&error]) {
// Handle Error
}
错误实例:
NSError *error;
[self trySomethingWithError:&error]
if (error) {
// Handle Error
}
11> 黄金路径:当使用条件语句编码时,左手边的代码应该是"golden" 或 “happy”路径。也就是不要嵌套if语句,多个返回语句也是OK:
实例:
- (void)someMethod {
if (![someOther boolValue]) {
return;
}
//Do something important
}
错误实例:
- (void)someMethod {
if ([someOther boolValue]) {
//Do something important
}
}
12> Case语句:大括号在case语句中并不是必须的,除非编译器强制要求。当一个case语句包含多行代码时,大括号应该加上;
实例1:
switch (condition) {
case 1:
// ...
break;
case 2: {
// ...
// Multi-line example using braces
break;
}
case 3:
// ...
break;
default:
// ...
break;
}
实例2(当相同代码被多个cases使用时,一个fall-through应该被使用。一个fall-through就是在case最后移除’break'语句,这样就能够允许执行流程跳转到下一个case值。为了代码更加清晰,一个fall-through需要注释一下):
switch (condition) {
case 1:
// ** fall-through! **
case 2:
// code executed for values 1 and 2
break;
default:
// ...
break;
}
实例3(当在switch使用枚举类型时,’default’是不需要的):
RWTLeftMenuTopItemType menuType = RWTLeftMenuTopItemMain;
switch (menuType) {
case RWTLeftMenuTopItemMain:
// ...
break;
case RWTLeftMenuTopItemShows:
// ...
break;
case RWTLeftMenuTopItemSchedule:
// ...
break;
}
三、私有方法及变量声明
1>声明位置:在.m文件中最上方,定义空的category进行声明:
#import "CodeStandardViewController.h"
/** 此类作用注解 */
@interface CodeStandardViewController ()
// 声明私有变量
@property(nonatomic, weak) UICollectionView *collectionView;
// 私有方法
- (void)samplePrivateMethod;
@end
@implementation CodeStandardViewController
// 私有方法的实现
- (void)samplePrivateMethod {
//some code
}
三. 关于注释
最好的代码是不需要注释的,尽量通过合理的命名;
良好的代码把含义表达清楚,在必要的地方添加注释;
注释需要与代码同步更新;
如果做不到命名尽量的见名知意的话,就可以适当的添加一些注释或者mark;
1> 属性注释(如下:)
/// 学生
@property (nonatomic, strong) Student *student;
2> 方法声明注释:
/// 登录验证
///
/// @param personId 用户名
/// @param password 密码
/// @param complete 执行完毕的block
///
/// @return
+ (void)loginWithPersonId:(NSString *)personId password:(NSString *)password complete:(void (^)(CheckLogon *result))complete;
四. 关于UI布局
使用Interface Builder进行界面布局:Xib文件的命名与其对应的.h文件保持相同;
五. 格式化代码
1> 指针 "*" 位置:定义一个对象时,指针 "*" 靠近变量(如: NSString*userName;)
2> 方法的声明和定义:在 - 、+ 和 返回值 之间留一个空格,方法名和第一个参数之间不留空格;在方法各个段之间应该也有一个空格(符合Apple的风格);在参数前应该包含一个具有描述性的关键字来描述参数;”and”这个词的用法应该保留,它不应该用于多个参数来说明;
例如:
- (id)viewWithTag:(NSInteger)tag
{.. .}
- (void)setExampleText:(NSString *)text image:(UIImage *)image
{.. .}
- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag
{.. .}
- (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height
{.. .}
错误实例:
- (instancetype)initWithWidth:(CGFloat)width andHeight:(CGFloat)height;{.. .}
- (instancetype)initWith:(int)width and:(int)height
{.. .}
3> 代码缩进
•使用 xcode 默认缩进,即 tab = 4空格
•使用 xcode 中 re-indent 功能定期对代码格式进行整理
•相同类型变量声明需要独行声明(如下:)
CGRect frame = self.view.frame;
CGFloat oringX = frame.origin.x;
CGFloat oringY = frame.origin.y;
CGFloat lineWidth = frame.size.width;
•Method与Method之间空一行,且方法后的括号与方法应缩为一行,中间以一个空格间隙分隔(视觉上更清晰和更易于组织):
#pragma mark - private methods
- (void)samplePrivateMethod
{...}
- (void)sampleForIf
{...}
4> 对method进行分组(考虑):使用#pragma mark -方式对类的方法进行分组:
#pragma mark - private methods
- (void)samplePrivateMethod
{...}
- (void)sampleForIf
{...}
- (void)sampleForWhile
{...}
- (void)sampleForSwitch
{...}
#pragma mark - public methods
- (void)samplePublicMethodWithParam:(NSString*)sampleParam
{...}
5> 大括号写法
•对于类的method: 左括号另起一行写(遵循苹果官方文档)
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
•对于其他使用场景: 左括号跟在第一行后边,中间以一个空格分隔
- (void)sampleForIf
{
BOOL someCondition = YES;
if(someCondition) {
// do something here
}
}
- (void)sampleForWhile
{
int i = 0;
while (i < 10) {
// do something here
i = i + 1;
}
}
- (void)sampleForSwitch
{
SampleEnum testEnum = SampleEnumTwo;
switch(testEnum) {
caseSampleEnumUndefined: {
// do something
break;
}
caseSampleEnumOne: {
// do something
break;
}
caseSampleEnumTwo: {
// do something
break;
}
default:{
NSLog(@"WARNING: there is an enum type not handled properly!");
break;
}
}
•任何需要写大括号的部分,不得省略
错误示例:
- (void)wrongExamples
{
BOOLsomeCondition = YES;
if (someCondition)
NSLog(@"this is wrong!!!");
while(someCondition)
NSLog(@"this is wrong!!!");
}