iOS Developer Libray (中文版)-- Defining Classes 定义类

该篇是我自己学习iOS开发时阅读文档时随手记下的翻译,有些地方不是很准确,但是意思还是对的,毕竟我英语也不是很好,很多句子无法做到准确的字词翻译,大家可以当做参考,有错误欢迎指出,以后我会尽力翻译的更好,大家一起努力共同进入,有兴趣的同学可以一起学习。

注:部分图片没有上传,可以点我下载源文件;

Defining Classes 定义类

When you write software for OS X or iOS, most of your time is spent working with objects. Objects in Objective-C are just like objects in other object-oriented programming languages: they package data with related behavior.

当你写OS X或iOS软件时,你的大部分时间会花费在对象上,对象对于OC就是对象对于其他面向对象的编程语言一样:他们处理数据包相关的事情。

An app is built as a large ecosystem of interconnected objects that communicate with each other to solve specific problems, such as displaying a visual interface, responding to user input, or storing information. For OS X or iOS development, you don’t need to create objects from scratch to solve every conceivable problem; instead you have a large library of existing objects available for your use, provided by Cocoa (for OS X) and Cocoa Touch (for iOS).

一款应用的开发就是在建立一个大的对象沟通的生太系统用来解决一个明确的问题,比如可视化界面,用来响应用户输入,或者存储信息。对于OS X 或 iOS开发,你没必要为解决一个问题从零开始创建每一个对象,Cocoa (for OS X) 和Cocoa Touch (for iOS)提供了大量的基础对象供你使用。

Some of these objects are immediately usable, such as basic data types like strings and numbers, or user interface elements like buttons and table views. Some are designed for you to customize with your own code to behave in the way you require. The app development process involves deciding how best to customize and combine the objects provided by the underlying frameworks with your own objects to give your app its unique set of features and functionality.

一些对象可以直接使用,比如基本的数据类型像字符串和数字,或者用户界面(图形界面)元素像按钮表格之类的。一些是是为了让你定制自己的方法而设计的。应用开发包含怎么定制和组合基本框架和你的类,是你的应用拥有独特的功能。

In object-oriented programming terms, an object is an instance of a class. This chapter demonstrates how to define classes in Objective-C by declaring an interface, which describes the way you intend the class and its instances to be used. This interface includes the list of messages that the class can receive, so you also need to provide the class implementation, which contains the code to be executed in response to each message.

在面向对象的编程语言中,对象是类的实例。这一章讲解了如何在OC中通过声明接口定义类,接口描述了类及如何使用它,这个接口定义了类可以接收的消息的列表,所以你还需要提供类的实现,它包含每一个消息的执行的代码。(个人理解:应该是定义一系列方法,并实现方法,至于为什么使用message,应该是从方法使用的本质是消息的传递的角度理解,可能不对,有大神发现错误希望指出,谢谢!)

Classes Are Blueprints for Objects 类是对象的蓝图

A class describes the behavior and properties common to any particular type of object. For a string object (in Objective-C, this is an instance of the class NSString), the class offers various ways to examine and convert the internal characters that it represents. Similarly, the class used to describe a number object (NSNumber) offers functionality around an internal numeric value, such as converting that value to a different numeric type.

类描述了属性和行为,任何类都是这样。对于一个字符串对象(OC中是NSString类的一个实例),类提供了一系列方法来审视和转换它的性质。同样的,用来表示数字的类NSNumber围绕着数值提供了一系列的方法,比如在不同的数字类型之间转换。

In the same way that multiple buildings constructed from the same blueprint are identical in structure, every instance of a class shares the same properties and behavior as all other instances of that class. Every NSString instance behaves in the same way, regardless of the internal string of characters it holds.

就像多个建筑采用结构相同的蓝图,同一个类的实例拥有一样的属性和方法,任何NSString的实例都有一样的方法,无论它内部的自读是什么。

Any particular object is designed to be used in specific ways. You might know that a string object represents some string of characters, but you don’t need to know the exact internal mechanisms used to store those characters. You don’t know anything about the internal behavior used by the object itself to work directly with its characters, but you do need to know how you are expected to interact with the object, perhaps to ask it for specific characters or request a new object in which all the original characters are converted to uppercase.

任何一个特殊的类都有自己的用处,你知道字符串对象用来存储字符串,但是你没必要知道他的内部到底是如何存储这些字符串的。你不知道对象使用自己特性的内部的工作方式。但是你应该知道你期望对象做什么,也许是需要他的一个属性,或者请求一个所有字符都转换为大写的新对象。

In Objective-C, the class interface specifies exactly how a given type of object is intended to be used by other objects. In other words, it defines the public interface between instances of the class and the outside world.

在OC中,类的接口会指定一个给定类型的对象怎么被其他对象使用,总之,它定义类的实例和外面世界之间的接口。(个人理解:也就是说接口是类内部与外界交流的窗口)

Mutability Determines Whether a Represented Value Can Be Changed

可变的类

Some classes define objects that are immutable. This means that the internal contents must be set when an object is created, and cannot subsequently be changed by other objects. In Objective-C, all basic NSString and NSNumber objects are immutable. If you need to represent a different number, you must use a new NSNumber instance.

一些类规定对象是不可变的,这意味着在创建对象的时候必须设定他的内容,而且之后不能被其他对象改变,在OC中,所有基本的NSString和NSNumber对象都是不可变的。如果你需要表示不同的数,你必须使用一个新的NSNumber对象。

Some immutable classes also offer a mutable version. If you specifically need to change the contents of a string at runtime, for example by appending characters as they are received over a network connection, you can use an instance of theNSMutableString class. Instances of this class behave just like NSString objects, except that they also offer functionality to change the characters that the object represents.

一些不可变得类提供了一些可变版本,如果你需要在运行时改变某个字符串的值,比如添加一个网络接收到的字符,你可以使用NSMutableString的对象,NSMutableString的实对象和NSString对象一样,但是它提供了改变字符串的值的方法。

Although NSString and NSMutableString are different classes, they have many similarities. Rather than writing two completely separate classes from scratch that just happen to have some similar behavior, it makes sense to make use of inheritance.

尽管,NSString 和NSMutableString是不同额的类,但是他们很多地方都一样,相对于从头写两个全新的类来实现他们的功能,继承看起来似乎更有用。

Classes Inherit from Other Classes  继承

In the natural world, taxonomy classifies animals into groups with terms like species, genus, and family. These groups are hierarchical, such that multiple species may belong to one genus, and multiple genera to one family.

在自然界,分类学将生物分组为物种、属、科(大概这个意思,这三个英文单词我真的没办法区分他们具体的代表意思,而且对生物的界、门、纲、目、科、属、种也早就抛到九霄云外了。)这些群体是分层的,这样多个物种可能属于一个属,多个属可能属于一个科。

Gorillas, humans, and orangutans, for example, have a number of obvious similarities. Although they each belong to different species, and even different genera, tribes, and subfamilies, they are taxonomically related since they all belong to the same family (called “Hominidae”), as shown in Figure 1-1.

比如:大猩猩、人类和猩猩有很多相似的部分,尽管他们都属于不同的物种,甚至不同的属、部落、亚科(又是这个奇葩的分类),但是他们是都属于同一个科的关系(叫做”人科“),如图所示:Figure 1-1(就是下面那个…………)

Figure 1-1  Taxonomic relationships between species

In the world of object-oriented programming, objects are also categorized into hierarchical groups. Rather than using distinct terms for the different hierarchical levels such as genus or species, objects are simply organized into classes. In the same way that humans inherit certain characteristics as members of the Hominidae family, a class can be set to inherit functionality from a parent class.

总而言之在面向对象的编程体系中,对象也分为层组。与使用层次如属、种的分类方式不同,对象通过类简单的实现分组。与人类继承人科动物的某些特征一样,一个类可以从父类继承一些功能。

When one class inherits from another, the child inherits all the behavior and properties defined by the parent. It also has the opportunity either to define its own additional behavior and properties, or override the behavior of the parent.

当一个类继承其他的类,子类会继承父类所有的属性和方法。子类可以定义或添加自己的属性和方法,或者重写父类的方法。(要不然要子类何用之有!!!)

In the case of Objective-C string classes, the class description for NSMutableString specifies that the class inherits from NSString, as shown in Figure 1-2. All of the functionality provided by NSString is available in NSMutableString, such as querying specific characters or requesting new uppercase strings, but NSMutableString adds methods that allow you to append, insert, replace or delete substrings and individual characters.

在OC中字符串类,NSMutableString 继承NSString(如图1-2)所有NSString的方法,NSMutableString都有,比如查找某一字符、生成新的大写字符串。但是NSMutableString添加一些方法,使你可以执行插入、替换、或删除子串或某一个字符的操作。

Figure 1-2  NSMutableString class inheritance

The Root Class Provides Base Functionality

In the same way that all living organisms share some basic “life” characteristics, some functionality is common across all objects in Objective-C.

就像所有活着的生物都有一些生命的基本特性,有一些方法是所有OC对象都具有的。

When an Objective-C object needs to work with an instance of another class, it is expected that the other class offers certain basic characteristics and behavior. For this reason, Objective-C defines a root class from which the vast majority of other classes inherit, called NSObject. When one object encounters another object, it expects to be able to interact using at least the basic behavior defined by the NSObject class description.

当一个OC对象需要和其他类的对象一起工作,我们期望另一个类有基本的属性和方法。因此,OC定义了一个大多数类都继承的根类NSObject。当一个对象遇到其他对象,我们希望他们至少可以通过NSObject定义的基本方法互动。

When you’re defining your own classes, you should at a minimum inherit from NSObject. In general, you should find a Cocoa or Cocoa Touch object that offers the closest functionality to what you need and inherit from that.

当你定义自己的类的时候,你至少需要继承自NSObject,通常你需要继承Cocoa或Cocoa Touch中一个和你需要的功能比较相似的类。

If you want to define a custom button for use in an iOS app, for example, and the provided UIButton class doesn’t offer enough customizable attributes to satisfy your needs, it makes more sense to create a new class inheriting from UIButton than fromNSObject. If you simply inherited from NSObject, you’d need to duplicate all the complex visual interactions and communication defined by the UIButton class just to make your button behave in the way expected by the user. Furthermore, by inheriting from UIButton, your subclass automatically gains any future enhancements or bug fixes that might be applied to the internal UIButton behavior.

比如,如果你想在自己的iOS应用上自定义一个按钮,而且UIButton类不能提供足够的可供修改的属性来满足你的需求,创建一个新的类继承自NSObject或许会更有用。如果你简单的继承自NSObject。为了使你的按钮能够正常工作你需要重写UIButton复杂的可视化和交互功能。此外,继承自UIButton你的子类会自动获得将来添加的功能或BUG修复(不知道是不是我理解错了,感觉这里语言逻辑怪怪的,仅仅针对这句话的意思来看是支持你继承UIButton,这样你就可以获得官方更新带来的好处,但是前面面熟说满足不了自定义的需要啊!!所以下面给出了解释)。

The UIButton class itself is defined to inherit from UIControl, which describes basic behavior common to all user interface controls on iOS. The UIControl class in turn inherits from UIView, giving it functionality common to objects that are displayed on screen. UIView inherits from UIResponder, allowing it to respond to user input such as taps, gestures or shakes. Finally, at the root of the tree, UIResponder inherits from NSObject, as shown in Figure 1-3.

UIButton的定义继承自UIControl,UIControl定义了iOS所有的基本的用户交互方法。UIControl继承自UIView,UIView使它有了在屏幕上显示的能力,UIView继承自UIResponder,允许它响应用户输入如:轻拍、手势或摇动,最终UIResponder继承自NSObject,如下图(尽管直译不是这个意思)。

Figure 1-3  UIButton class inheritance

This chain of inheritance means that any custom subclass of UIButton would inherit not only the functionality declared by UIButton itself, but also the functionality inherited from each superclass in turn. You’d end up with a class for an object that behaved like a button, could display itself on screen, respond to user input, and communicate with any other basic Cocoa Touch object.

这条链意味着任何一个继承UIButton的类都不只是继承了UIButton自己,同样继承了以上所有的父类。你想要一个和UIButton功能类似的类(你需要的是对象,但是需要定义类,原话表达了这个意思,能力有限,无法翻译的那么完美,只好注释了),可以在屏幕上显示自己,响应输入、可以和其他的Cocoa Touch对象沟通。

It’s important to keep the inheritance chain in mind for any class you need to use, in order to work out exactly what it can do. The class reference documentation provided for Cocoa and Cocoa Touch, for example, allows easy navigation from any class to each of its superclasses. If you can’t find what you’re looking for in one class interface or reference, it may very well be defined or documented in a superclass further up the chain.

为了实现你想要的功能,继承自继承链的哪一个类非常重要。比如:Cocoa 和Cocoa Touch的类的参考文档,让你非常容易的找到一个类的父类,如果你在一个类的声明或者参考中找不到想要找的,那么他很可能定义在他的父类或者父类链中。

The Interface for a Class Defines Expected Interactions

One of the many benefits of object-oriented programming is the idea mentioned earlier—all you need to know in order to use a class is how to interact with its instances. More specifically, an object should be designed to hide the details of its internal implementation.

面向对象编程的好处之一是上面提到的你只需要知道如何使用一个类和他的实例。然而,设计一个对象我们需要隐藏他的实现细节。

If you use a standard UIButton in an iOS app, for example, you don’t need to worry about how pixels are manipulated so that the button appears on screen. All you need to know is that you can change certain attributes, such as the button’s title and color, and trust that when you add it to your visual interface, it will be displayed correctly and behave in the way you expect.

比如:你在iOS应用上使用一个标准的UIButton,你不必关系像素如何工作才使得按钮显示在屏幕上。你只需要知道,修改某些属性,比如按钮的标题、颜色,然后把它添加到界面,他就会正确的显示出来。

When you’re defining your own class, you need to start by figuring out these public attributes and behaviors. What attributes do you want to be accessible publicly? Should you allow those attributes to be changed? How do other objects communicate with instances of your class?

当你自定义类时,开始你应该确定哪些属性和方法是公开的。你想让哪些属性公开?这些属性是不是可变?其他的对象怎么和你的类生成的对象通讯?

This information goes into the interface for your class—it defines the way you intend other objects to interact with instances of your class. The public interface is described separately from the internal behavior of your class, which makes up the class implementation. In Objective-C, the interface and implementation are usually placed in separate files so that you only need to make the interface public.

这些信息需要定义在你的接口中,它定义了其他对象和你的类的实例的交互方式。类的声明和内部的如何实现部分是分开的。在OC中,类接口和实现通常写在不同的文件中,所以你可以只公开接口。

Basic Syntax 基本语法

The Objective-C syntax used to declare a class interface looks like this:

OC中像这样定义类的接口:”

@interface SimpleClass : NSObject

关键字 类名:父类(继承自谁,冒号后是谁)

 

@end

This example declares a class named SimpleClass, which inherits from NSObject.

这个例子声明类的名字是: SimpleClass,继承自:NSObject

The public properties and behavior are defined inside the @interface declaration. In this example, nothing is specified beyond the superclass, so the only functionality expected to be available on instances of SimpleClass is the functionality inherited from NSObject.

公开的属性和方法定义在@interface中。在这个例子中,没有什么自定义的属性和方法,所以SimpleClass 只有继承自NSObject的属性和方法

Properties Control Access to an Object’s Values 属性

Objects often have properties intended for public access. If you define a class to represent a human being in a record-keeping app, for example, you might decide you need properties for strings representing a person’s first and last names.

对象通常有公开属性。如果你在一个档案类应用中定一个用来表示人的类,比如:你可能需要字符串类的属性来表示人的姓和名。

Declarations for these properties should be added inside the interface, like this:

这些属性应该声明在接口中,如下:

@interface Person : NSObject

 

@property NSString *firstName;

关键字:类型:属性

@property NSString *lastName;

 

@end

In this example, the Person class declares two public properties, both of which are instances of the NSString class.

在这个例子中,Person类声明了两个公开属性,他们都是NSSting类型的。

Both these properties are for Objective-C objects, so they use an asterisk to indicate that they are C pointers. They are also statements just like any other variable declaration in C, and therefore require a semi-colon at the end.

他们都是OC对象,所以使用星号(*)指出他们是C的指针,他们和其他C变量的声明一样,所以结尾也需要一个分好(;)【注意以上符号都是英文的,包括空格】

You might decide to add a property to represent a person’s year of birth to allow you to sort people in year groups rather than just by name. You could use a property for a number object:

你或许会添加一个属性来表示人的年龄,这样你就可以按照年龄排序而不是姓名,你可以使用一个数字对象。

@property NSNumber *yearOfBirth;

but this might be considered overkill just to store a simple numeric value. One alternative would be to use one of the primitive types provided by C, which hold scalar values, such as an integer:

但是仅仅因为一个数字这样可能显得太过了(通俗说:杀鸡焉用牛刀),另一种方式是使用C提供的基本数据类型,比如integer(我记得C是int,尽管在OC中integer就是int,但是这么写让我很不爽……)

@property int yearOfBirth;

Property Attributes Indicate Data Accessibility and Storage Considerations

属性的属性用来表示数据的可访问性和存储方面的考虑(我知道这么说好2,但是属性的属性是事实,第一个属性意思是类的属性【如上面的firstName、lastName】,第二个属性是用来描述第一个属性的特征的,熟悉的人应该懂得,比如【readOnly……】)

 

The examples shown so far all declare properties that are intended for complete public access. This means that other objects can both read and change the values of the properties.

以上所有的例子中声明的都是公开属性,这意味着其他的对象可以任意的读取和更改属性的信息。

In some cases, you might decide to declare that a property is not intended to be changed. In the real world, a person must fill out a large amount of paperwork to change their documented first or last name. If you were writing an official record-keeping app, you might choose that the public properties for a person’s name be specified as read-only, requiring that any changes be requested through an intermediary object responsible for validating the request and approving or denying it.

有些情况下,你可能希望属性不可被修改。在真实世界中,一个人必须填写一大堆文件才能改变他们的姓或者名,如果你在写一个官方的文档类应用,你可以把人名这个公开属性定义成只读的,这样任何更改它的请求都会被拒绝。

Objective-C property declarations can include property attributes, which are used to indicate, among other things, whether a property is intended to be read-only. In an official record-keeping app, the Person class interface might look like this:

OC属性的声明可以同时声明属性的属性,用来表示,在其他属性之外,有一个属性被声明是只读的,在一个官方的档案应用中,人的类可能看起来会像这样。

@interface Person : NSObject

@property (readonly) NSString *firstName;

关键字(属性的属性)类型 参数名

@property (readonly) NSString *lastName;

@end

Property attributes are specified inside parentheses after the @property keyword, and are described fully in Declare Public Properties for Exposed Data.

属性的属性写在“@property”后面的括号中,详细信息:在这里

Method Declarations Indicate the Messages an Object Can Receive

方法确定了对象可接收的消息类型

The examples so far have involved a class describing a typical model object, or an object designed primarily to encapsulate data. In the case of a Person class, it’s possible that there wouldn’t need to be any functionality beyond being able to access the two declared properties. The majority of classes, however, do include behavior in addition to any declared properties.

目前为止所有的例子都是数据模型了类,或者设计的主要目的是封装数据。比如Person类,他可能不需要任何函数就可以直接访问它的两个公开属性。然而,大多数类除了属性声明外还包含方法的声明。

Given that Objective-C software is built from a large network of objects, it’s important to note that those objects can interact with each other by sending messages. In Objective-C terms, one object sends a message to another object by calling a method on that object.

考虑到OC软件是建立在一个大的对象网络上的,对象能通过发送消息与其他对象互相影响便显得尤为重要。在OC中,一个对象通过调用另一个对象方法的方式来发送消息。

Objective-C methods are conceptually similar to standard functions in C and other programming languages, though the syntax is quite different. A C function declaration looks like this:

OC的方法在概念上与标准C语言或者其他编程语言很相似,虽然他们的语法有一些区别。一个标准的C方法看起来像这样:

void SomeFunction();

返回值类型 方法名

The equivalent Objective-C method declaration looks like this:

一个标准的OC方法看起来像这样:

- (void)someMethod;

方法类型 (返回值类型)方法名

In this case, the method has no parameters. The C void keyword is used inside parentheses at the beginning of the declaration to indicate that the method doesn’t return any value once it’s finished.

这里,这个方法没有参数,C的关键字void放在方法开头的小括号里,表示该方法没有任何返回值。

The minus sign (-) at the front of the method name indicates that it is an instance method, which can be called on any instance of the class. This differentiates it from class methods, which can be called on the class itself, as described in Objective-C Classes Are also Objects.

 

开头的减号(-)表示该方法是一个对象方法,任何该对象的实例都拥有这个方法(字面来看是被调用,这个看怎么理解了,不过意思表达的还ok,就是说每一个该类new出来的对象都会有这个减号方法)。和它不同的是类方法,类方法职能由类来调用,详见:点上面的链接。

 

As with C function prototypes, a method declaration inside an Objective-C class interface is just like any other C statement and requires a terminating semi-colon.

与C的函数原型一样,一个OC类接口的声明和其他C的声明一样,需要在结尾添加一个“;”

Methods Can Take Parameters    参数

If you need to declare a method to take one or more parameters, the syntax is very different to a typical C function.

如果你的方法需要传参,语法和C有很大不同。

For a C function, the parameters are specified inside parentheses, like this:

对于C函数,参数卸载小括号里面,像这样:

void SomeFunction(SomeType value);

返回值类型 方法名(参数类型 参数)

An Objective-C method declaration includes the parameters as part of its name, using colons, like this:

OC把参数的声明当做函数名的一部分,用“:”表示,像这样;

- (void)someMethodWithValue:(SomeType)value;

方法类型 (返回值)方法名:(参数类型)参数;

As with the return type, the parameter type is specified in parentheses, just like a standard C type-cast.

和返回值类型类似,参数的类型放在小括号中,有点像C的类型转换。

If you need to supply multiple parameters, the syntax is again quite different from C. Multiple parameters to a C function are specified inside the parentheses, separated by commas; in Objective-C, the declaration for a method taking two parameters looks like this:

如你你想传多个参数,语法和C又有一些不同,C的多个参数都是定义在一个小括号里面,用逗号分开。在OC中,两个参数的声明方式如下:

- (void)someMethodWithFirstValue:(SomeType)value1 secondValue:(AnotherType)value2;

方法类型 方法名的一部分:(参数类型)参数 方法名的一部分:(参数类型)参数名;

In this example, value1 and value2 are the names used in the implementation to access the values supplied when the method is called, as if they were variables.

在这个例子中,value1和value2是实现该方法时被调用的名称,如果他们是变量。(这句不是很懂,整体表达的意思是这两个参数的名字是value1和value2,你可以在实现该方法的时候使用它们)

Some programming languages allow function definitions with so-called named arguments; it’s important to note that this is not the case in Objective-C. The order of the parameters in a method call must match the method declaration, and in fact thesecondValue: portion of the method declaration is part of the name of the method:

一些编程语言允许命名参数(简单说可以理解为没必要按顺序传参),OC中没有这个特性,参数必须按声明的顺序传入,事实上,secondValue部分也是方法名的一部分。

someMethodWithFirstValue:secondValue:注意:这里只有方法名,没有参数与

This is one of the features that helps make Objective-C such a readable language, because the values passed by a method call are specified inline, next to the relevant portion of the method name, as described in You Can Pass Objects for Method Parameters.

这一特点有助于提高OC的可读性,因为通过调用方法的参数被内联,旁边就是方法名中相关的部分。参阅:点上面。

Note: The value1 and value2 value names used above aren’t strictly part of the method declaration, which means it’s not necessary to use exactly the same value names in the declaration as you do in the implementation. The only requirement is that the signature matches, which means you must keep the name of the method as well as the parameter and return types exactly the same.

注:像value1和value2这种命名方式不是必须的,这意味着你没必要在实现和声明中使用完全一样的参数名。参数只要求签名匹配,也就是说你只需要保证方法名以及参数和返回值的类型相同即可。

As an example, this method has the same signature as the one shown above:

例:下面这个方法与上面的方法具有一样的签名;

- (void)someMethodWithFirstValue:(SomeType)info1 secondValue:(AnotherType)info2;

These methods have different signatures to the one above:

下面这两个方法的签名不一样

- (void)someMethodWithFirstValue:(SomeType)info1 anotherValue:(AnotherType)info2;

- (void)someMethodWithFirstValue:(SomeType)info1 secondValue:(YetAnotherType)info2;

Class Names Must Be Unique 类名唯一

It’s important to note that the name of each class must be unique within an app, even across included libraries or frameworks. If you attempt to create a new class with the same name as an existing class in a project, you’ll receive a compiler error.

需要注意的是,在一个应用中每一个类的名字都必须是唯一的,包括系统的库和框架。如果你尝试创建一个和已存在的类一样名字的类,你会收到编译错误。

For this reason, it’s advisable to prefix the names of any classes you define, using three or more letters. These letters might relate to the app you’re currently writing, or to the name of a framework of reusable code, or perhaps just your initials.

因此,在自定义类前加个前缀是个明智的选择,三个字符或以上都可以(非强制,也就是说你不加完全没问题,只要你有办法区分类。)这些字母可以和你当前应用名相关、或者一个可重用的框架名、或者只是你姓名的首字母。

All examples given in the rest of this document use class name prefixes, like this:

在本文档中,之后出现的其他例子中,类名都会用同一个前缀,如下:

@interface XYZPerson : NSObject

@property (readonly) NSString *firstName;

@property (readonly) NSString *lastName;

@end

Historical Note: If you’re wondering why so many of the classes you encounter have an NS prefix, it’s because of the past history of Cocoa and Cocoa Touch. Cocoa began life as the collected frameworks used to build apps for the NeXTStep operating system. When Apple purchased NeXT back in 1996, much of NeXTStep was incorporated into OS X, including the existing class names. Cocoa Touch was introduced as the iOS equivalent of Cocoa; some classes are available in both Cocoa and Cocoa Touch, though there are also a large number of classes unique to each platform.

简史:你过你对为什么有如此多的NS前缀的类?因为Cocoa和Cocoa Touch的历史。Cocoa最初是做为NeXTStep系统开发应用的框架集出现的,1996年,当苹果收购NeXT时候,很多NeXTStep的东西被兼并到了OS X,包括那那些已存在的类名。Cocoa Touch 和Cocoa一起被引进了iOS,有些类可在这两个框架中都可以使用,但是也有很多是他们独有的。

Two-letter prefixes like NS and UI (for User Interface elements on iOS) are reserved for use by Apple.

连个字母的前缀NS和UI(iOS用户界面元素)被苹果保留。

Method and property names, by contrast, need only be unique within the class in which they are defined. Although every C function in an app must have a unique name, it’s perfectly acceptable (and often desirable) for multiple Objective-C classes to define methods with the same name. You can’t define a method more than once within the same class declaration, however, though if you wish to override a method inherited from a parent class, you must use the exact name used in the original declaration.

和方法名一样,每个类里面的属性名在本类中也必须是唯一的。虽然在一个C应用中,每一个方法名都必须是唯一的,但是在OC中不同类拥有一样的名字的方法是完全可以接受的(通常是可取的)。在一个类的声明中,你不能定义一个方法超过一次(我觉得只能定义一次说起来更舒服),然而,你想重写继承自父类的一个方法,必须使用和父类声明中一样的函数名。

As with methods, an object’s properties and instance variables (described in Most Properties Are Backed by Instance Variables) need to be unique only within the class in which they are defined. If you make use of global variables, however, these must be named uniquely within an app or project.

和方法名一样,一个对象的属性和变量(参阅:点上面)在定义它的类中必须是唯一的。如果你想使用全局变量,无论如何,都必须让它在你的应用或者项目中有一个独特的名字,。

Further naming conventions and suggestions are given in Conventions.

更多命名规范和建议参阅:点上面;

The Implementation of a Class Provides Its Internal Behavior  接口的实现

Once you’ve defined the interface for a class, including the properties and methods intended for public access, you need to write the code to implement the class behavior.

一旦你定义了一个包含公开属性和方法的类,必须要编码实现他的功能。

As stated earlier, the interface for a class is usually placed inside a dedicated file, often referred to as a header file, which generally has the filename extension .h. You write the implementation for an Objective-C class inside a source code file with the extension .m.

像之前说的一样,一个类的声明通常放在一个以.h为扩展名的单独文件中,叫做头文件。你写的实现类的代码放在一个.m结尾的扩展文件中。

Whenever the interface is defined in a header file, you’ll need to tell the compiler to read it before trying to compile the implementation in the source code file. Objective-C provides a preprocessor directive, #import, for this purpose. It’s similar to the C#include directive, but makes sure that a file is only included once during compilation.

因为接口被定义在头文件中,所以在编译源代码之前你需要告诉编译器先读头文件。OC提供了一个预编译指令。#import,他和C中的#include功能相似,但是可以保证相同文件只被编译一次。

Note that preprocessor directives are different from traditional C statements and do not use a terminating semi-colon.

注意:不同于传统的C,OC中的预编译命令无须分号结尾。

Basic Syntax 基本语法

The basic syntax to provide the implementation for a class looks like this:

基本的实现语法如下:

#import "XYZPerson.h"

预编译指令

 

@implementation XYZPerson

关键字 类名

 

@end

If you declare any methods in the class interface, you’ll need to implement them inside this file.

你在接口中定义的任何方法,都需要在这个文件中实现。

Implementing Methods

For a simple class interface with one method, like this:

做一个简单的类的声,如下:

@interface XYZPerson : NSObject

- (void)sayHello;

@end

the implementation might look like this:

实现如下:

#import "XYZPerson.h"

 

@implementation XYZPerson

- (void)sayHello {

    NSLog(@"Hello, World!");

}

@end

This example uses the NSLog() function to log a message to the console. It’s similar to the standard C library printf() function, and takes a variable number of parameters, the first of which must be an Objective-C string.

例子中使用NSLog()方法输入消息到控制台,它的功能和C中的printf()相似,它的参数是可变的,但是第一个必须是OC字符串。

Method implementations are similar to C function definitions in that they use braces to contain the relevant code. Furthermore, the name of the method must be identical to its prototype, and the parameter and return types must match exactly.

方法的实现和C方法相似,用大括号({})把相关的代码括起来,此外,方法名必须和定义的相同,参数和返回值的类型也必须匹配。

Objective-C inherits case sensitivity from C, so this method:

OC继承C的大小写敏感,所以下面的方法:

- (void)sayhello {

}

would be treated by the compiler as completely different to the sayHello method shown earlier.

会被编译器当做和sayHello 完全不同的两个方法。

In general, method names should begin with a lowercase letter. The Objective-C convention is to use more descriptive names for methods than you might see used for typical C functions. If a method name involves multiple words, use camel case (capitalizing the first letter of each new word) to make them easy to read.

通常,方法名以小写字母开头,与典型的C函数名不同,OC使用表达能力更强的方法名。如果方法名有多个单词,采用驼峰命名法(每个单词的开头大写)可以使他更容易阅读。

Note also that whitespace is flexible in Objective-C. It’s customary to indent each line inside any block of code using either tabs or spaces, and you’ll often see the opening left brace on a separate line, like this:

注意,OC中空格是灵活的提示。通常我们使用制表符或换行符控制缩进,代码中经常可以看到左花括号单独一行,如下:

- (void)sayHello

{

    NSLog(@"Hello, World!");

}

Xcode, Apple’s integrated development environment (IDE) for creating OS X and iOS software, will automatically indent your code based on a set of customizable user preferences. See Changing the Indent and Tab Width in Xcode Workspace Guide for more information.

OS X和iOS的开发的集成环境XCode,会根据你的设定自动缩进,更多相关信息在:Xcode Workspace Guide (书名吧)

You’ll see many more examples of method implementations in the next chapter, Working with Objects.

你将会看到很多实现的例子在:点上面

Objective-C Classes Are also Objects OC的类也是对象

In Objective-C, a class is itself an object with an opaque type called Class. Classes can’t have properties defined using the declaration syntax shown earlier for instances, but they can receive messages.

在OC中,类是一个不透明的对象叫做Class,类不能使用声明定义属性,但是可以接收消息。

The typical use for a class method is as a factory method, which is an alternative to the object allocation and initialization procedure described in Objects Are Created Dynamically. The NSString class, for example, has a variety of factory methods available to create either an empty string object, or a string object initialized with specific characters, including:

类的一个典型应用是工厂模式,它替代对象的创建和初始化过程,详见:点上面。比如NSString类,有很多方法创建一个空串或者根据指定字符创建字符串,方法如下:

+ (id)string;

+ (id)stringWithString:(NSString *)aString;

+ (id)stringWithFormat:(NSString *)format, …;

+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error;

+ (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc;

As shown in these examples, class methods are denoted by the use of a + sign, which differentiates them from instance methods using a - sign.

如例所示,用加号(+)区分类方法和对象方法。

Class method prototypes may be included in a class interface, just like instance method prototypes. Class methods are implemented in the same way as instance methods, inside the @implementation block for the class.

类方法的声明和对象方法一样,定义在接口中。类似的,也在implementation中实现。

Exercises 习题

Note: In order to follow the exercises given at the end of each chapter, you may wish to create an Xcode project. This will allow you to make sure that your code compiles without errors.

注:每一章的练习题,你都可以创建一个XCode项目,确保你的代码是正确的。

Use Xcode’s New Project template window to create a Command Line Tool from the available OS X Application project templates. When prompted, specify the project’s Type as Foundation.

使用XCode的新项目模板窗口创建一个命令行工具,从可用的OS X模板中选择,当出现提示时,悬着基础类型。

  1. Use Xcode’s New File template window to create the interface and implementation files for an Objective-C class called XYZPerson, which inherits from NSObject.

使用Xcode新文件模板窗口创建OC类的接口和实现文件,类名是XYZPerson继承NSobject。

  1. Add properties for a person’s first name, last name and date of birth (dates are represented by the NSDate class) to the XYZPerson class interface.

为XYZPerson添加姓、名和生日(用NSDate类)属性。

  1. Declare the sayHello method and implement it as shown earlier in the chapter.

仿照本章之前的例子,声明并实现一个sayHello方法。

  1. Add a declaration for a class factory method, called “person”. Don’t worry about implementing this method until you’ve read the next chapter.

为该类添加一个叫“person”的工厂方法,在阅读下一章之前,不用管怎么实现它。

Note: If you’re compiling the code, you’ll get a warning about an “Incomplete implementation” due to this missing implementation.

注:如果你编译代码,会收到一个警告:不完整的实现。因为你没有实现工厂方法。

 

posted @ 2016-02-25 00:47  孔凡凯凯  阅读(329)  评论(0编辑  收藏  举报