Cocoa Style
For Objective-C
[原文链接:http://cocoadevcentral.com/articles/000082.php]
Putting Thought into Naming
Cocoa 强烈推荐保护足够信息明确没有歧义的命名方式.达到看名知意
class name
capitalized 大写
Objective-C doesn't have namespaces, so prefix your class names with initials
前缀 以示 区分
如GATableView GAEmail
subclass a standard Cocoa class
继承自cocoa库的类 要带有父类的名称 如 GAmyTableView
Variable Names
首单词的首字母小写,其后的单词的首字母大写 以示区分.
NSString * streetAddress = @"城守东大街";
NSString * cityName = @"成都";
NSString * countyName = @"中国";
命名要清晰明确,胜过于简洁.
Correct
NSString * hostName;
NSNumber * ipAddress;
NSArray * accounts;
Incorrect
NSString * HST_NM; // all caps and too terse
NSNumber * theip; // a word or abbreviation?
NSMutableArray * nsma; // completely ambiguous
变量命不能以数字开头,不能添加空格,不能添加除下划线以外的特殊字符.
Apple discourages using an underscore as a prefix for a private instance variable.
apple公司不建议使用以下划线开始的私有实例变量命
如"
NSString * name //
correct! NSString * _name // _incorrect_
Variable Names: Indicating Type
在变量命中表明类型
一般说来
NSString, NSArray, NSNumber or BOOL 类型的变量命名时 不用带类型名称.
但其他类型的变量最好在变量命中标示类型.
Correct
NSString * accountName;
NSMutableArray * mailboxes;
NSArray * defaultHeaders;
BOOL userInputWasUpdated;
OK, But Not Ideal
NSString * accountNameString;
NSMutableArray * mailboxArray;
NSArray * defaultHeadersArray;
BOOL userInputWasUpdatedBOOL;
When to Indicate Type
NSImage * previewPaneImage; // self-explanatory
NSProgressIndicator * uploadIndicator; // shows progress for uploads
NSFontManager * fontManager; // only one of these, basic name ok
在命名NSArray,NSSet时 如果变量命中有复数意思可以不表示出Mutable
/*灰色地带--需要商讨下*/
Method Names
从方法名字就能了解这个方法的功能作用.
如:
[fileWrapper writeToFile: path atomically: YES updateFilenames: YES];
把fileWrapper 写到磁盘上去,保存路径为path
Programmers do much more reading of code than writing
Objective-C and Cocoa are designed to read well
Method Names: Accessors
在属性的存取方法中
读取方法 并不是加get前缀
而保存方法中 始终带有set前缀
Correct!
- (NSString *) name;
- (NSString *) color;
name = [object name];
color = [object color];
[object setName: name];
[object setColor: color];
而get前缀 一般使用一个方法,可以让你通过内存地址该间的接获取到一个变量.
The "get" prefix is, however, used in situations when you're returning a value indirectly via a memory address:
/*翻译有问题. */
如下
When to Use "Get" Prefix
// copy objects from the NSArray to the buffer
id *buffer = (id *) malloc(sizeof(id) * [array count]);
[array getObjects: buffer];
Adjectives
并不是所有属性都返回的是名词如name,height,date 属性多是反映一个对象的特殊性质. 有事会修改为性用词.特别想bool类型的属性.
如selectable
in Objective-C, the getter for this key is called -isSelectable, but the setter is -setSelectable:
需要注意的是遵循这些规则来命名你的存取方法不只是为了保证代码清晰整齐.更重要的是Cocoa的神奇的KVCkey-value coding编码方式,kvc 正是基于适当地命名存取方法.
Abbreviations
简写
虽然一直都在说尽可能避免简写,但是一些常用的简写仍可保留
int max min TIFF HTTP URL HTML PDF rect temp info JPG FTP RTF XML ASCII
Preprocessor Contants / Macros
预处理和宏定义
和 ANSI C一样 预处理宏定义都使用大写
如
#define MAX_ENTRIES 20
#ifdef ENABLE_BINDINGS_SUPPORT
[代码编程规范][代码样式][cocoa]Cocoa Style For Objective-C 上
最新推荐文章于 2024-09-21 01:00:06 发布