Objective-C 苹果开发文档 10 Conventions

来源:互联网 发布:proteus单片机仿真使用 编辑:程序博客网 时间:2024/06/05 02:02

Conventions

当你处理框架类的时候,你可能注意到OC的代码很容易阅读。OC中的类和方法名,与一般的C代码函数或者C标准库中的名称相比更具有描述性,许多字符的名称需要使用驼峰命名法。当你在编写你自己的类时,你应该遵守由Cocoa和Cocoa Touch提供的惯例,这样可以使她们的可读性更好,为了你和其他的OC开发者,请保持你代码的一致性。

除此之外,许多OC和框架特性需要你严格遵守命名惯例,这是为了让各种机制可以正确运行。例如,访问器方法名字必须遵守惯例,为了处理像KVC或者KVO这样的技术。

本章包含了一些Cocoa 和Cocoa Touch中常用的惯例,解释了为什么名字在整个应用程序中必须是唯一的原因,包括在她的关联框架中。


Some Names Must Be Unique Across Your App

每次你创建一个新的类型,符号或者标识符,你都应该首先考虑这个范围内你的名字是唯一的。有时候,范围可能包括整个应用,包括她的关联框架;有时候,范围被限定在一个类中或者只是一个block中。

Class Names Must Be Unique Across an Entire App


OC类的名字必须是唯一的,不仅仅是在你编写的工程中的代码,也包括任何其他的框架或者你包含进来的软件集中。例如,你应该避免使用一般的类名像ViewController或者TextParser,因为可能一个你包含的框架也使用了这样的名字,你的程序可能因此失败,

为了事类名变得唯一,惯例就是使用前缀。你会注意到Cocoa和Cocoa Touch类名典型的是以NS或者UI开头的。两个字符的前缀被Apple使用在框架里里面了。随着你对Cocoa和Cocoa Touch的学习深入,你会遇到许多其他的涉及到具体框架的前缀:

Prefix

Framework

NS

Foundation (OS X and iOS) and Application Kit (OS X)

UI

UIKit (iOS)

AB

Address Book

CA

Core Animation

CI

Core Image

你自己的类应该使用三个字符的前缀!这些字符可能与你的公司名字和你的应用有关,或者即使是你应用中的一个特殊的组件。例如,如果你的公司叫Whispering Oak,你开发了一个游戏叫Zebra Surprise,你可以选择WZS或者WOZ作为前缀。

你应该使用一个名词为你的类命名,这样会使得她变得很容易理解类代表什么,如下:

You should also name your classes using a noun that makes it clear what the class represents, like these examples from Cocoa and Cocoa Touch:

NSWindow

CAAnimation

NSWindowController

NSManagedObjectContext

If multiple words are needed in a class name, you should use camel case by capitalizing the first letter of each subsequent word.

如果一个类名中需要很多的词,要使用驼峰命名法。

Method Names Should Be Expressive and Unique Within a Class


一旦你为一个类选择了一个 唯一的名字,那么类中声明的方法也需要是唯一的名字。惯例是在另一个类中的方法使用相同的名字,例如,重写一个父类的方法,或者利用多态性。在许多类中方法实现同样的任务,应该有同样的名字,返回值和参数类型。

Method names do not have a prefix, and should start with a lowercase letter; camel case is used again for multiple words, like these examples from the NSString class:

length

characterAtIndex:

lengthOfBytesUsingEncoding:

If a method takes one or more arguments, the name of the method should indicate each parameter:

substringFromIndex:

writeToURL:atomically:encoding:error:

enumerateSubstringsInRange:options:usingBlock:

The first portion of the method name should indicate the primary intent or result of calling the method. If a method returns a value, for example, the first word normally indicates what will be returned, like the lengthcharacter... and substring... methods shown above. Multiple words are used if you need to indicate something important about the return value, as with themutableCopycapitalizedString or lastPathComponent methods from the NSString class. If a method performs an action, such as writing to disk or enumerating the contents, the first word should indicate that action, as shown by the write... and enumerate... methods.

第一部分的方法名称应当指明主要意图或调用方法的结果。如果一个方法返回一个值,例如,第一个单词通常表示将返回,如长度、字符……和子串……上面所示的方法。使用多个单词如果需要显示一些重要的返回值,与mutableCopy一样,从NSString capitalizedString或lastPathComponent方法类。如果一个方法执行一个操作,比如写入磁盘或列举的内容,第一个字应表明行动,如图所示的写……和列举……方法。

If a method includes an error pointer parameter to be set if an error occurred, this should be the last parameter to the method. If a method takes a block, the block parameter should be the last parameter in order to make any method invocations as readable as possible when specifying a block inline. For the same reason, it’s best to avoid methods that take multiple block arguments, wherever possible.

如果一个方法包含一个错误指针参数设置如果发生错误,这应该是方法最后一个参数。如果一个方法接受一个块,块参数应该是最后一个参数以使在指定一个内联块任何方法调用尽可能的可读。出于同样的原因,最好避免使用多个块参数的方法,尽可能。

It’s also important to aim for clear but concise method names. Clarity doesn’t necessarily mean verbosity but brevity doesn’t necessarily result in clarity, so it’s best to aim for a happy medium:

定义一个目标明确但是却很简易的方法名也很重要。清晰并不一定意味着冗长但简洁并不一定导致清晰,因此最好找一个快乐的媒介:

stringAfterFindingAndReplacingAllOccurrencesOfThisString:withThisString:

Too verbose

strReplacingStr:str:

Too concise

stringByReplacingOccurrencesOfString:withString:

Just right

避免使用方法名的缩写词,除非你确定这个缩写的用法在其他的语言和环境中也是被广泛熟知的。普遍的缩写详见 Acceptable Abbreviations and Acronyms。

Always Use a Prefix for Method Names in Categories on Framework Classes


当你使用类别为一个存在的框架类添加一个方法时,你应该在方法名之前包含前缀,以避免冲突的问题,详见Avoid Category Method Name Clashes。

Local Variables Must Be Unique Within The Same Scope

Because Objective-C is a superset of the C language, the C variable scope rules also apply to Objective-C. A local variable name must not clash with any other variables declared within the same scope:

因为OC是C语言的超集,C变量范围规则同样适用于OC。一个局部变量名必须不能和其他的在同一个范围之内的变量声明有冲突:

- (void)someMethod {
    int interestingNumber = 42;
    ...
    int interestingNumber = 44; // not allowed
}

Although the C language does allow you to declare a new local variable with the same name as one declared in the enclosing scope, like this:

尽管C语言允许你声明一个新的同名的局部变量在作用域中:

- (void)someMethod {
    int interestingNumber = 42;
    ...
    for (NSNumber *eachNumber in array) {
        int interestingNumber = [eachNumber intValue]; // not advisable
        ...
    }
}

这样使得代码看起来多少有些困惑,因此只要有可能,就不要这样使用。

Some Method Names Must Follow Conventions

In addition to considering uniqueness, it’s also essential for a few important method types to follow strict conventions. These conventions are used by some of the underlying mechanisms of Objective-C, the compiler and runtime, in addition to behavior that is required by classes in Cocoa and Cocoa Touch.

除了考虑唯一性,为少数一些重要的方法类型遵守严格的惯例也是基本的。这些惯例是OC的一些潜在的机制,编译器和运行时使用的,除了Cocoa和Cocoa Touch需要的行为。


Accessor Method Names Must Follow Conventions


例如,当你使用@property语法为一个对象声明属性的时候,就像Encapsulating Data中描述的那样,编译器会自动的合成相关的get和set方法(除非你另有指定)。如果你需要提供你自己的访问器方法实现,确保你使用正确的方法名很重要,这是为了让你的方法可以通过点语法调用。

除非另有指定,否则get方法必须使用和属性一样的命名。如果一个属性调用是firstName,那么访问器方法也应该叫firstName。对于Boolean类型的属性是个例外,因为她的get方法应该以is开头。例如,一个属性叫paused,那么她的get方法应该叫isPaused。

属性的set方法应该使用这种形式setPropertyName:。例如一个属性叫firstName,那么set方法应该叫setFirstName:;对于Boolean类型来说,如果属性叫paused,那么set方法应该叫setPaused:。

尽管@property语法允许你指定不同的访问器方法名,但是你应该只是在像Boolean这样的情况下使用她。基本上你应该遵守这些惯例,否则当你使用像KVC(可以获取或者设置属性通过ValueForKey:和setValue:forKey)这样的技术时,不遵守惯例就不能使用。详见Key-Value Coding Programming Guide.


Object Creation Method Names Must Follow Conventions


正如你前面看到的那样,总是有许多办法创建一个类的实例。你可以使用分配和初始化器结合的形式,像这样:

    NSMutableArray *array = [[NSMutableArray alloc] init];

or use the new convenience method as an alternative to calling alloc and init explicitly:

或者使用new便利方法代替上面的方法:

    NSMutableArray *array = [NSMutableArray new];

一下类也提供类工厂方法:

    NSMutableArray *array = [NSMutableArray array];

类工厂方法应该总是以类名(没有前缀)作为方法名的,除非是现有的类的子类。例如,在NSArray类中,工厂方法是array开头的。NSMutableArray类没有定义她自己的工厂方法,因此可变数组的工厂方法命名的开头仍然是array。

有许多的内存管理规则支持者OC,编译器使用这些规则确保对象有合理的生命周期。尽管对于这些规则你不需要担心太多,编译器会基于创建的方法名判定那个规则应该被遵守。通过工厂方法创建的对象的管理很明显不同于通过分配和初始化创建或者new创建的方法,因为使用了自动释放池block的缘故。详见 Advanced Memory Management Programming Guide.


0 0
原创粉丝点击