Google的Objective-C编码规范解读
【Google的Objective-C编码规范】 Objective-C是一种基于C语言的扩展,强调动态特性和面向对象设计,是Mac OS X和iOS开发的主要语言。Cocoa是Mac OS X的主要应用框架,包含一系列Objective-C类,用于快速构建功能丰富的OS X应用程序。Apple提供了一套广泛接受的Objective-C编程规范,而Google则有其C++编程规范。Google的Objective-C编码规范结合了Apple和Google的最佳实践,同时考虑了Objective-C++的使用情况。遵循这一规范时,应注意已存在于Google C++规范中的禁止条款同样适用于Objective-C,除非本规范中明确指出不同。Google Toolbox for Mac项目(GTM)中包含了符合此规范的开源代码,为其他项目提供了参考实现。本规范并不是Objective-C的入门教程,假设读者已经具备基本的Objective-C语言知识。示例代码如下: objc // GTMFoo.h // FooProject // Created by Greg Miller on 6/13/08. // Copyright 2008 Google, Inc. All rights reserved. // #import // 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 also be adjacent to the object they're // documenting. // (no blank line between this comment and the interface) @interface GTMFoo : NSObject { @private NSString *foo_; NSString *bar_; } + (id)fooWithString:(NSString *)string; - (id)initWithString:(NSString *)string; - (NSString *)foo; - (void)setFoo:(NSString *)newFoo; - (GTMFoo *)doWorkWithBlah:(NSString *)blah; @end
关键点总结:1. 注释:所有顶级声明(如@interface、category、协议)都需要注释,并紧贴声明。2. 空行:接口与注释间无空行,但属性间需空行提高可读性。3. 初始化方法:-initWithString:
为指定初始化器。4. 方法命名:动词+名词形式如-setFoo:
,+fooWithString:
。5. 变量命名:私有变量加下划线前缀,如foo_
。
评论区