Objective-C编码规范

it2024-04-16  12

本文参考Apple & Google Objective-C编码规范,根据个人的编码习惯,总结出一些通用的编码规则。

代码示例

头文件示例代码

下面是用Objective-C语言编写的规范的头文件示例代码。

// // BTFoo.h // CodingGuidelines // // Created by Tracy E on 12-8-13. // Copyright (c) 2012年 ChinaMWorld Inc. All rights reserved. // #import <Foundation/Foundation.h> /** A sample class demonstrating good Objective-C style. All interfaces, categories, and protocols (read: all top-level declarations in a header) MUST be commented. Comments must alse be adjacent to the object they're documenting. */ @protocol BTFooDelegate; @interface BTFoo : NSObject{ @private NSString *_bar; CGFloat _price; @public NSString *_name; id<BTFooDelegate> _delegate; } @property (nonatomic, copy) NSString *name; //the name of Foo. default is nil. @property (nonatomic, assign) id<BTFooDelegate> delegate; //weak reference. default is nil. /** initializer. |string| will be copied and assigned to |_name|. @param string The foo name. @return an autorelease instance of BTFoo. */ - (id)initWithString:(NSString *)string; /** Designated initailizer. initialize a new BTFoo object. @param name The model name. @param number The model number. @param price The model price. @return a newly initialized object. */ - (id)initFooWithModelName:(NSString *)name modelNumber:(NSUInteger)number modelPrice:(CGFloat)price; /** Dosomething... @param name The model name. @param number The model number. @param price The model price. */ - (void)doName:(NSString *)name modelNumber:(NSUInteger)number modelPrice:(CGFloat)price; //Gets and Sets |_bar|. - (NSString *)bar; - (void)setBar:(NSString *)bar; @end

 

源文件示例代码

下面是用Objective-C语言编写的规范的源文件示例代码。

// // BTFoo.m // CodingGuidelines // // Created by Tracy E on 12-8-13. // Copyright (c) 2012年 ChinaMWorld Inc. All rights reserved. // #import "BTFoo.h" @interface BTFoo (PrivateMethods) + (id)fooWithString:(NSString *)string; @end @implementation BTFoo @synthesize name = _name; @synthesize delegate = _delegate; - (void)dealloc{ [_bar release]; [_name release]; [super dealloc]; } - (id)initWithString:(NSString *)string{ self = [super init]; if (self) { _name = [string copy]; _bar = [[NSString alloc] initWithFormat:@"bar"]; } return self; } - (id)initFooWithModelName:(NSString *)name modelNumber:(NSUInteger)number modelPrice:(CGFloat)price{ self = [BTFoo fooWithString:name]; if (self) { _price = price; } return self; } - (void)doName:(NSString *)name modelNumber:(NSUInteger)number modelPrice:(CGFloat)price{ } - (NSString *)bar{ return _bar; } - (void)setBar:(NSString *)bar{ [_bar autorelease]; _bar = [bar copy]; } #pragma mark BTFoo Private Methods + (id)fooWithString:(NSString *)string{ return [[[BTFoo alloc] initWithString:string] autorelease]; } - (void)doSomethingWith:(BTFoo *)theFoo rect:(CGRect)theRect interval:(float)theInterval{ //... } - (void)short:(BTFoo *)theFoo longKeyword:(CGRect)theRect evenLongerKeyword:(float)theInterval{ //... } @end

 

间距与格式

程序中代码的排版,缩进,间隔等可以根据IDE的具体设置而决定,但最终都应该使代码的间距与格式统一,达到整齐美观的效果。

指针的位置

类型与“*”之间一个空格,“*”与变量名之间没有空格。

NSString *_text;

每行代码的长度

每行代码的长度不超过100个字符。每行代码的字符数可通过IDE进行设置。(设置:XCode —> Preferences —> Text Editing —> Page guide at column : 100)

方法的声明与定义

声明方法时,在 - 或 + 与返回类型之间应该留一个空格的间距。参数表的参数之间不要留间隔。

星号(*)前的空格是必须的。

- (id)initWithString:(NSString *)string;

如果参数过多,每个参数应各占一行。在有多行参数的情况下,每行参数前的冒号应对齐。

- (void)doSomethingWith:(BTFoo *)theFoo rect:(CGRect)theRect interval:(float)theInterval{ //... }

当第一行的函数关键字比其后面行的关键字短时,后面的行应缩进四个空格。保证后续的关键字垂直对齐,而不应该采用冒号对齐的方式。

- (void)short:(BTFoo *)theFoo longKeyword:(CGRect)theRect evenLongerKeyword:(float)theInterval{ //... }

方法的调用

如果调用的方法没有超出一行(100字符长),则所有参数在同一行。

[item1 setTitle:@"提交" forState:UIControlStateNormal];

如果调用的方法过长,则每个参数占用一行,以冒号对其。

[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

如果调用的方法过长,但方法名比参数名短,每个参数一行,缩进四个空格竖直对齐。

[self short:myFoo longKeyword:rect eventLongerKeyword:10];

@public 与 @private的使用

使用权限控制符@public 和@private 应缩进两个空格。

@interface MyClass : NSObject{ @private NSInteger _count; @public NSString *_title; } @end

协议的使用

在类型标识符与协议的名之间不应该有空格。此协议使用的规范适用于类的声明、成员变量的声明以及方法的声明

@protocol MyClassDelegate; @interface MyClass : NSObject{ @private id<MyClassDelegate> _delegate; } @property (nonatomic, assign) id<MyClassDelegate> delegate;

如果申明中包含多个protocal且超出一行时换行,缩进两个空格。

@interface CustomViewController : UIViewController<UITableViewDataSource, UITableViewDataSource, UITextFieldDelegate, UISearchBarDelegate>{ }

@property,@synthesize,@dynamic的使用

@property与左括号之间留一个空格。

@property和@synthesize的缩进级别与@interface或者@implementation的缩进级别相同。

@property的声明语句应该紧跟在类的成员变量声明语句块的后面。

@synthesize的实现语句应该紧跟在@implementation语句之后。

@interface BTAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end @implementation BTAppDelegate @synthesize window = _window;

命名规范

文件的命名

文件的名字应该反映其中包含的类名字,也应该遵循项目的风格习惯。

文件扩展命的使用规范如下:

.hC/C++/Objective-C头文件.mObjective-C源文件.mmObjective-C++源文件.cc纯C++源文件.cC源文件

类的命名

类名应该用大写开头的驼峰命名法。

MyTableView、HomeViewController

在应用程序级别的代码中,尽量不要使用带前缀的类名。每个类都有相同的前缀不能提高可读性。如果是编写多个应用程序间的共用代码,那么需要为类名加上前缀。

Category的命名

Category的命名应该包含2-3个字符的前缀,用于说明Category是属于具体的某个工程的。

当声明一个Category时,Category的左括号与类名之间应该留一个空格的间隔。

例如要实现NSString的一个Category,用于实现解析功能。Category的文件名应该命名为NSString+GTMParsing.h,而Category的名字为GTMStringParsingAdditions,Category的名字与文件名不一致的原因是,在NSString+GTMParsing.h的文件中,可以声明多个用于解析功能的NSString类的Category。

Objective-C方法命名

1.方法应使用小写开头的驼峰法命名,每个参数都应该小写开头。

2.方法名应该尽可能读起来像一句话,参数名就如同方法名的补充说明(比如convertPoing:fromRect: 或者 replaceCharactersInRange:withString: )。

3.方法明中要避免单词缩写。

- (void)setBGImage:(UIImage *)img; //避免 - (void)setBackgroundImage:(UIImage *)image; //推荐

变量的命名

变量名应使用小写开头的驼峰法命名。

类成员变量名应该以一个下划线开始。

常量(预定义,枚举,局部常量等)使用小写k开头的驼峰法。例如:

localVariable; //局部变量 _instanceVariable; //成员变量 kConstant; //常量

注释

文件的注释

每个文件的开头都应该包含以下的注释。

1.文件名。

2.项目名称。

3.文件的创建者。

4.创建日期。

5.版权说明。

6.必要时还应包含许可声明。(如:Apache 2.0, BSD, LGPL, GPL)

声明的注释

对每个接口,类别,协议进行声明时,都应该有用于解释其功能或者如何使用的注释。

每个方法/函数声明时,都应该有用于解释其功能,参数值,返回值的注释,必要时还应该说明方法/函数的使用注意事项。

当类的成员变量可用于多线程访问时,应该对其使用做出详细的说明和解释。

//A delegate for NSApplication to handle notifications about app //launch and shut down. Owned by the main app controller. @interface AyAppDelegate : NSObject{ }@end

实现的注释

在为接口,类别,协议,方法/函数等的实现写注释时,应该使用竖线引用变量,函数名或者其他符号。

//Sometimes we need |count| to be less than zero. //Remember to call |StringWithSpaces("foo bar baz")|

属性的类型

应该严格的控制属性的类型(readonly, copy, retain, assign)

不允许外部修改的属性,使用readonly;

NSString类型使用copy而不是retain;

代理delegate使用assign,禁止使用retain。

注意事项

成员变量访问权限

成员变量应该尽可能地定义为@private。

重写指定初始化方法

当对一个类进行子类化时,一定要重写父类的指定初始化方法。如果没有正确重写父类的指定初始化方法,子类的初始化方法可能不会被调用,这会导致很多微妙而难以预测的错误。

初始化

没有必要在类的初始化方法中将成员变量的初始值设置为0或者nil。

//都是多余的 BOOL editable = NO; NSInteger currentIndex = 0; NSString *title = nil;

BOOL的使用

1.当将一个整型赋值给BOOL类型时应该特别注意,因为BOOL的类型为unsigned char。

2.不应该将BOOL类型的变量直接与YES进行比较

if(editable){/*推荐*/ } if(editable == YES){/*不推荐*/}

 

转载于:https://www.cnblogs.com/tracy-e/archive/2012/08/21/2648612.html

相关资源:数据结构—成绩单生成器
最新回复(0)