iOS Developer Libray (中文版)-- Defining Classes 定義類

該篇是我本身學習iOS開發時閱讀文檔時隨手記下的翻譯,有些地方不是很準確,可是意思仍是對的,畢竟我英語也不是很好,不少句子沒法作到準確的字詞翻譯,你們能夠當作參考,有錯誤歡迎指出,之後我會盡力翻譯的更好,你們一塊兒努力共同進入,有興趣的同窗能夠一塊兒學習。html

注:部分圖片沒有上傳,能夠點我下載源文件;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.api

當你寫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).app

一款應用的開發就是在創建一個大的對象溝通的生太系統用來解決一個明確的問題,好比可視化界面,用來響應用戶輸入,或者存儲信息。對於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.less

一些對象能夠直接使用,好比基本的數據類型像字符串和數字,或者用戶界面(圖形界面)元素像按鈕表格之類的。一些是是爲了讓你定製本身的方法而設計的。應用開發包含怎麼定製和組合基本框架和你的類,是你的應用擁有獨特的功能。編程語言

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.ide

在面向對象的編程語言中,對象是類的實例。這一章講解了如何在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.

注:若是你編譯代碼,會收到一個警告:不完整的實現。由於你沒有實現工廠方法。

相關文章
相關標籤/搜索