Google的Objective-C编码规范
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Google的Objective-C编码规范
总览
背景知识
Objective-C是一个C语言的扩展语言,非常动态,非常的“面向对象”,它被设计成既拥有复杂的面向对象设计理念又可以轻松使用与阅读的语言,也是Mac OS X和iPhone开发的首选语言。
Cocoa是Mac OS X的主要应用框架,提供迅速开发各种功能的Mac OS X应用的Objective-C 类集合。
Apple已经有一个很好也被广泛接受的Objective-C的编程规范,Google也有类似的C++编程规范,这份Objective-C编程规范很自然是Apple和Google的共同推荐的组合。所以,在阅读本规范前,确保你已经阅读了:
Apple's Cocoa Coding Guidelines
Google's Open Source C++ Style Guide
注意所有已在Google的C++编程规范里的禁用条款在Objective-C里也适用,除非本文档明确指出反对意见。
本文档旨在描述可供可适用于所有Mac OS X代码的Objective-C(包括Objective-C++)编码规范和实践。规范中的许多条款已经改进也不断的被其他的项目和团队所证明其指导性。Google的相关开源项目都遵守此规范。
Google已经发布了一份作为Google Toolbox for Mac project (文档中简称为GTM)的组成部分的遵守本规范的开源代码。这份开放代码也是本文很好的例证(原文看不太懂--Code meant to be shared across different projects is a good candidate to be included in this repository. )
注意本文不是Objective-C的教学指南,我们假设读者已经了解语言。如果你是一个Objective-C 的初学者或需要重温,请阅读The Objective-C Programming Language .
示例
人们说一个例子胜过千言万语,所以就让我们用例子来让你感受以下编码规范的风格,留间距,命名等等。
下例是一份头文件,展示对@interface 声明正确的注释和留间距
// 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_;
}
// Returns an autoreleased instance of GMFoo. See -initWithString: for details // about the argument.
+ (id)fooWithString:(NSString *)string;
// Designated initializer. |string| will be copied and assigned to |foo_|.
- (id)initWithString:(NSString *)string;
// Gets and sets the string for |foo_|.
- (NSString *)foo;
- (void)setFoo:(NSString *)newFoo;
// Does some work on |blah| and returns YES if the work was completed
// successfuly, and NO otherwise.
- (BOOL)doWorkWithString:(NSString *)blah;
@end
下例是一份源文件,展示对接口的@implementation 的实现的正确注释和留间隔。它也包括了主要方法如getters,setters,init ,和dealloc 的相关实现。
//
// GTMFoo.m
// FooProject
//
// Created by Greg Miller on 6/13/08.
// Copyright 2008 Google, Inc. All rights reserved.
//
#import "GTMFoo.h"
@implementation GTMFoo
+ (id)fooWithString:(NSString *)string {
return [[[self alloc] initWithString:string] autorelease];
}