objectc 經(jīng)典入門教程_第1頁(yè)
objectc 經(jīng)典入門教程_第2頁(yè)
objectc 經(jīng)典入門教程_第3頁(yè)
objectc 經(jīng)典入門教程_第4頁(yè)
objectc 經(jīng)典入門教程_第5頁(yè)
已閱讀5頁(yè),還剩71頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、 Object-C 入門教程分類: Sip&asterisk2009-05-04 16:34 16409人閱讀 評(píng)論(2) 收藏 舉報(bào)大綱o 開(kāi)始吧下載這篇教學(xué)o 設(shè)定環(huán)境o 前言o 編譯 hello worldo 創(chuàng)建 Classesinterfaceo implementationo 把它們湊在一起o 詳細(xì)說(shuō)明.多重參數(shù)o 建構(gòu)子(Constructors)o 訪問(wèn)權(quán)限o Class level accesso 異常情況(Exceptions)處理o 繼承、多型(Inheritance, Polymorphism)以及其他面向?qū)ο蠊δ躨d 型別o 繼承(Inheritance)o

2、動(dòng)態(tài)識(shí)別(Dynamic types)o Categorieso Posingo Protocolso 內(nèi)存管理Retain and Release(保留與釋放)o Dealloco Autorelease Poolo Foundation Framework ClassesNSArrayo NSDictionary 優(yōu)點(diǎn)與缺點(diǎn) 更多信息開(kāi)始吧下載這篇教學(xué) 所有這篇初學(xué)者指南的原始碼都可以由 下載。這篇教學(xué)中的許多范例都是由 Steve Kochan 在 Programming in Objective-C. 一書中撰寫。如果你想得到更多詳細(xì)信息及范例,請(qǐng)直接參考該書。這個(gè)網(wǎng)站上登載的所有范例

3、皆經(jīng)過(guò)他的允許,所以請(qǐng)勿復(fù)制轉(zhuǎn)載。設(shè)定環(huán)境 Linux/FreeBSD: 安裝 GNUStep為了編譯 GNUstep 應(yīng)用程序,必須先執(zhí)行位于/usr/GNUstep/System/Makefiles/GNUstep.sh 的 GNUstep.sh 這個(gè)檔案。這個(gè)路徑取決于你的系統(tǒng)環(huán)境,有些是在 /usr, some /usr/lib,有些是/usr/local。如果你的 shell 是以 csh/tcsh 為基礎(chǔ)的 shell,則應(yīng)該改用 GNUStep.csh。建議把這個(gè)指令放在 .bashrc 或 .cshrc 中。 Mac OS X: 安裝 XCode Windows NT 5.X:

4、 安裝 cygwin 或 mingw,然后安裝 GNUStep前言 這篇教學(xué)假設(shè)你已經(jīng)有一些基本的 C 語(yǔ)言知識(shí),包括 C 數(shù)據(jù)型別、什么是函式、什么是回傳值、關(guān)于指針的知識(shí)以及基本的 C 語(yǔ)言內(nèi)存管理。如果您沒(méi)有這些背景知識(shí),我非常建議你讀一讀 K&R 的書:The C Programming Language(譯注:臺(tái)灣出版書名為 C 程序語(yǔ)言第二版)這是 C 語(yǔ)言的設(shè)計(jì)者所寫的書。 Objective-C,是 C 的衍生語(yǔ)言,繼承了所有 C 語(yǔ)言的特性。是有一些例外,但是它們不是繼承于 C 的語(yǔ)言特性本身。 nil:在 C/C+ 你或許曾使用過(guò) NULL,而在 Objective-C 中

5、則是 nil。不同之處是你可以傳遞訊息給 nil(例如 nil message;),這是完全合法的,然而你卻不能對(duì) NULL 如法炮制。 BOOL:C 沒(méi)有正式的布爾型別,而在 Objective-C 中也不是真的有。它是包含在 Foundation classes(基本類別庫(kù))中(即 import NSObject.h;nil 也是包括在這個(gè)頭文件內(nèi))。BOOL 在 Objective-C 中有兩種型態(tài):YES 或 NO,而不是 TRUE 或 FALSE。 #import vs #include:就如同你在 hello world 范例中看到的,我們使用了#import。#import 由

6、gcc 編譯程序支援。我并不建議使用 #include,#import基本上跟 .h 檔頭尾的 #ifndef #define #endif 相同。許多程序員們都同意,使用這些東西這是十分愚蠢的。無(wú)論如何,使用 #import 就對(duì)了。這樣不但可以避免麻煩,而且萬(wàn)一有一天 gcc 把它拿掉了,將會(huì)有足夠的 Objective-C 程序員可以堅(jiān)持保留它或是將它放回來(lái)。偷偷告訴你,Apple 在它們官方的程序代碼中也使用了 #import。所以萬(wàn)一有一天這種事真的發(fā)生,不難預(yù)料 Apple 將會(huì)提供一個(gè)支持 #import 的 gcc 分支版本。 在 Objective-C 中, method 及

7、 message 這兩個(gè)字是可以互換的。不過(guò)messages 擁有特別的特性,一個(gè) message 可以動(dòng)態(tài)的轉(zhuǎn)送給另一個(gè)對(duì)象。在Objective-C 中,呼叫對(duì)象上的一個(gè)訊息并不一定表示對(duì)象真的會(huì)實(shí)作這個(gè)訊息,而是對(duì)象知道如何以某種方式去實(shí)作它,或是轉(zhuǎn)送給知道如何實(shí)作的對(duì)象。編譯 hello world #import int main( int argc, const char *argv ) printf( hello world/n ); return 0; o 輸出hello world o 在 Objective-C 中使用 #import 代替 #include Objecti

8、ve-C 的預(yù)設(shè)擴(kuò)展名是 .m創(chuàng)建 classesinterface 基于 Programming in Objective-C, Copyright 2004 by Sams Publishing一書中的范例,并經(jīng)過(guò)允許而刊載。 #import interface Fraction: NSObject int numerator; int denominator; -(void) print; -(void) setNumerator: (int) d; -(void) setDenominator: (int) d; -(int) numerator; -(int) denominator

9、; end o NSObject:NeXTStep Object 的縮寫。因?yàn)樗呀?jīng)改名為 OpenStep,所以這在今天已經(jīng)不是那么有意義了。 繼承(inheritance)以 Class: Parent 表示,就像上面的 Fraction: NSObject。 夾在 interface Class: Parent . 中的稱為 instance variables。 沒(méi)有設(shè)定訪問(wèn)權(quán)限(protected, public, private)時(shí),預(yù)設(shè)的訪問(wèn)權(quán)限為protected。設(shè)定權(quán)限的方式將在稍后說(shuō)明。 Instance methods 跟在成員變數(shù)(即 instance variabl

10、es)后。格式為:scope (returnType) methodName: (parameter1Type) parameter1Name;scope 有class 或 instance 兩種。instance methods 以 - 開(kāi)頭,class level methods 以 + 開(kāi)頭。 Interface 以一個(gè) end 作為結(jié)束。implementation 基于 Programming in Objective-C, Copyright 2004 by Sams Publishing一書中的范例,并經(jīng)過(guò)允許而刊載。 #import Fraction.h #import imp

11、lementation Fraction -(void) print printf( %i/%i, numerator, denominator ); -(void) setNumerator: (int) n numerator = n; -(void) setDenominator: (int) d denominator = d; -(int) denominator return denominator; -(int) numerator return numerator; end o Implementation 以 implementation ClassName 開(kāi)始,以 end

12、 結(jié)束。 Implement 定義好的 methods 的方式,跟在 interface 中宣告時(shí)很近似。把它們湊在一起 基于 Programming in Objective-C, Copyright 2004 by Sams Publishing一書中的范例,并經(jīng)過(guò)允許而刊載。 #import #import Fraction.h int main( int argc, const char *argv ) / create a new instance Fraction *frac = Fraction alloc init; / set the values frac setNumer

13、ator: 1; frac setDenominator: 3; / print it printf( The fraction is: ); frac print; printf( /n ); / free memory frac release; return 0; o outputThe fraction is: 1/3 o Fraction *frac = Fraction alloc init;這行程序代碼中有很多重要的東西。 在 Objective-C 中呼叫 methods 的方法是 object method,就像 C+的 object-method()。 Objective-

14、C 沒(méi)有 value 型別。所以沒(méi)有像 C+ 的 Fraction frac; frac.print(); 這類的東西。在 Objective-C 中完全使用指針來(lái)處理對(duì)象。 這行程序代碼實(shí)際上做了兩件事: Fraction alloc 呼叫了 Fraction class 的 alloc method。這就像 malloc 內(nèi)存,這個(gè)動(dòng)作也做了一樣的事情。 object init 是一個(gè)建構(gòu)子(constructor)呼叫,負(fù)責(zé)初始化對(duì)象中的所有變量。它呼叫了 Fraction alloc 傳回的 instance 上的 init method。這個(gè)動(dòng)作非常普遍,所以通常以一行程序完成:Ob

15、ject *var = Object alloc init; frac setNumerator: 1 非常簡(jiǎn)單。它呼叫了 frac 上的 setNumerator method并傳入 1 為參數(shù)。 如同每個(gè) C 的變體,Objective-C 也有一個(gè)用以釋放內(nèi)存的方式: release。它繼承自 NSObject,這個(gè) method 在之后會(huì)有詳盡的解說(shuō)。詳細(xì)說(shuō)明.多重參數(shù) 目前為止我還沒(méi)展示如何傳遞多個(gè)參數(shù)。這個(gè)語(yǔ)法乍看之下不是很直覺(jué),不過(guò)它卻是來(lái)自一個(gè)十分受歡迎的 Smalltalk 版本。 基于 Programming in Objective-C, Copyright 2004 b

16、y Sams Publishing一書中的范例,并經(jīng)過(guò)允許而刊載。 . -(void) setNumerator: (int) n andDenominator: (int) d;. o . -(void) setNumerator: (int) n andDenominator: (int) d numerator = n; denominator = d; . o #import #import Fraction.h int main( int argc, const char *argv ) / create a new instance Fraction *frac = Fractio

17、n alloc init; Fraction *frac2 = Fraction alloc init; / set the values frac setNumerator: 1; frac setDenominator: 3; / combined set frac2 setNumerator: 1 andDenominator: 5; / print it printf( The fraction is: ); frac print; printf( /n ); / print it printf( Fraction 2 is: ); frac2 print; printf( /n );

18、 / free memory frac release; frac2 release; return 0; o output The fraction is: 1/3Fraction 2 is: 1/5 o 這個(gè) method 實(shí)際上叫做 setNumerator:andDenominator: 加入其他參數(shù)的方法就跟加入第二個(gè)時(shí)一樣,即 method:label1:label2:label3:,而呼叫的方法是 obj method: param1 label1: param2 label2: param3 label3: param4 Labels 是非必要的,所以可以有一個(gè)像這樣的 met

19、hod:method:,簡(jiǎn)單的省略label 名稱,但以 : 區(qū)隔參數(shù)。并不建議這樣使用。建構(gòu)子(Constructors) 基于 Programming in Objective-C, Copyright 2004 by Sams Publishing一書中的范例,并經(jīng)過(guò)允許而刊載。 . -(Fraction*) initWithNumerator: (int) n denominator: (int) d;. o . -(Fraction*) initWithNumerator: (int) n denominator: (int) d self = super init; if ( se

20、lf ) self setNumerator: n andDenominator: d; return self; . o #import #import Fraction.h int main( int argc, const char *argv ) / create a new instance Fraction *frac = Fraction alloc init; Fraction *frac2 = Fraction alloc init; Fraction *frac3 = Fraction alloc initWithNumerator: 3 denominator: 10;

21、/ set the values frac setNumerator: 1; frac setDenominator: 3; / combined set frac2 setNumerator: 1 andDenominator: 5; / print it printf( The fraction is: ); frac print; printf( /n ); printf( Fraction 2 is: ); frac2 print; printf( /n ); printf( Fraction 3 is: ); frac3 print; printf( /n ); / free mem

22、ory frac release; frac2 release; frac3 release; return 0; o output The fraction is: 1/3 Fraction 2 is: 1/5Fraction 3 is: 3/10 o interface 里的宣告就如同正常的函式。 implementation 使用了一個(gè)新的關(guān)鍵詞:super如同 Java,Objective-C 只有一個(gè) parent class(父類別)。 使用 super init 來(lái)存取 Super constructor,這個(gè)動(dòng)作需要適當(dāng)?shù)睦^承設(shè)計(jì)。 你將這個(gè)動(dòng)作回傳的 instance 指派給

23、另一新個(gè)關(guān)鍵詞:self。Self 很像C+ 與 Java 的 this 指標(biāo)。 if ( self ) 跟 ( self != nil ) 一樣,是為了確定 super constructor 成功傳回了一個(gè)新對(duì)象。nil 是 Objective-C 用來(lái)表達(dá) C/C+ 中 NULL 的方式,可以引入 NSObject 來(lái)取得。 當(dāng)你初始化變量以后,你用傳回 self 的方式來(lái)傳回自己的地址。 預(yù)設(shè)的建構(gòu)子是 -(id) init。 技術(shù)上來(lái)說(shuō),Objective-C 中的建構(gòu)子就是一個(gè) init method,而不像 C+ 與Java 有特殊的結(jié)構(gòu)。訪問(wèn)權(quán)限 預(yù)設(shè)的權(quán)限是 protecte

24、d Java 實(shí)作的方式是在 methods 與變量前面加上 public/private/protected 修飾語(yǔ),而 Objective-C 的作法則更像 C+ 對(duì)于 instance variable(譯注:C+術(shù)語(yǔ)一般稱為 data members)的方式。 #import interface Access: NSObject public int publicVar; private int privateVar; int privateVar2; protected int protectedVar; end o #import Access.h implementation A

25、ccessend o #import Access.h #import int main( int argc, const char *argv ) Access *a = Access alloc init; / works a-publicVar = 5; printf( public var: %i/n, a-publicVar ); / doesnt compile /a-privateVar = 10; /printf( private var: %i/n, a-privateVar ); a release; return 0; o outputpublic var: 5 o 如同

26、你所看到的,就像 C+ 中 private: list of vars public: list of vars 的格式,它只是改成了private, protected, 等等。Class level access 當(dāng)你想計(jì)算一個(gè)對(duì)象被 instance 幾次時(shí),通常有 class level variables 以及class level functions 是件方便的事。 #import static int count; interface ClassA: NSObject +(int) initCount; +(void) initialize;end o #import Class

27、A.h implementation ClassA -(id) init self = super init; count+; return self; +(int) initCount return count; +(void) initialize count = 0; end o #import ClassA.h #import int main( int argc, const char *argv ) ClassA *c1 = ClassA alloc init; ClassA *c2 = ClassA alloc init; / print count printf( ClassA

28、 count: %i/n, ClassA initCount ); ClassA *c3 = ClassA alloc init; / print count again printf( ClassA count: %i/n, ClassA initCount ); c1 release; c2 release; c3 release; return 0; o output ClassA count: 2ClassA count: 3 o static int count = 0; 這是 class variable 宣告的方式。其實(shí)這種變量擺在這里并不理想,比較好的解法是像 Java 實(shí)作

29、static class variables 的方法。然而,它確實(shí)能用。 +(int) initCount; 這是回傳 count 值的實(shí)際 method。請(qǐng)注意這細(xì)微的差別!這里在 type 前面不用減號(hào) - 而改用加號(hào) +。加號(hào) + 表示這是一個(gè) class level function。(譯注:許多文件中,class level functions 被稱為 class functions 或 class method) 存取這個(gè)變數(shù)跟存取一般成員變數(shù)沒(méi)有兩樣,就像 ClassA 中的 count+ 用法。 +(void) initialize method is 在 Objective-

30、C 開(kāi)始執(zhí)行你的程序時(shí)被呼叫,而且它也被每個(gè) class 呼叫。這是初始化像我們的 count 這類 class level variables 的好地方。異常情況(Exceptions) 注意:異常處理只有 Mac OS X 10.3 以上才支持。 基于 Programming in Objective-C, Copyright 2004 by Sams Publishing一書中的范例,并經(jīng)過(guò)允許而刊載。 #import interface CupWarningException: NSExceptionend o #import CupWarningException.h impleme

31、ntation CupWarningExceptionend o #import interface CupOverflowException: NSExceptionend o #import CupOverflowException.h implementation CupOverflowExceptionend o #import interface Cup: NSObject int level; -(int) level; -(void) setLevel: (int) l; -(void) fill; -(void) empty; -(void) print;end o #impo

32、rt Cup.h #import CupOverflowException.h #import CupWarningException.h #import #import implementation Cup -(id) init self = super init; if ( self ) self setLevel: 0; return self; -(int) level return level; -(void) setLevel: (int) l level = l; if ( level 100 ) / throw overflow NSException *e = CupOver

33、flowException exceptionWithName: CupOverflowException reason: The level is above 100 userInfo: nil; throw e; else if ( level = 50 ) / throw warning NSException *e = CupWarningException exceptionWithName: CupWarningException reason: The level is above or at 50 userInfo: nil; throw e; else if ( level

34、0 ) / throw exception NSException *e = NSException exceptionWithName: CupUnderflowException reason: The level is below 0 userInfo: nil; throw e; -(void) fill self setLevel: level + 10; -(void) empty self setLevel: level - 10; -(void) print printf( Cup level is: %i/n, level ); end o #import Cup.h #im

35、port CupOverflowException.h #import CupWarningException.h #import #import #import #import int main( int argc, const char *argv ) NSAutoreleasePool *pool = NSAutoreleasePool alloc init; Cup *cup = Cup alloc init; int i; / this will work for ( i = 0; i 4; i+ ) cup fill; cup print; / this will throw ex

36、ceptions for ( i = 0; i 7; i+ ) try cup fill; catch ( CupWarningException *e ) printf( %s: , e name cString ); catch ( CupOverflowException *e ) printf( %s: , e name cString ); finally cup print; / throw a generic exception try cup setLevel: -1; catch ( NSException *e ) printf( %s: %s/n, e name cStr

37、ing, e reason cString ); / free memory cup release; pool release; o output Cup level is: 10 Cup level is: 20 Cup level is: 30 Cup level is: 40 CupWarningException: Cup level is: 50 CupWarningException: Cup level is: 60 CupWarningException: Cup level is: 70 CupWarningException: Cup level is: 80 CupWa

38、rningException: Cup level is: 90 CupWarningException: Cup level is: 100 CupOverflowException: Cup level is: 110CupUnderflowException: The level is below 0 o NSAutoreleasePool 是一個(gè)內(nèi)存管理類別?,F(xiàn)在先別管它是干嘛的。 Exceptions(異常情況)的丟出不需要擴(kuò)充(extend)NSException 對(duì)象,你可簡(jiǎn)單的用 id 來(lái)代表它: catch ( id e ) . 還有一個(gè) finally 區(qū)塊,它的行為就像

39、Java 的異常處理方式,finally 區(qū)塊的內(nèi)容保證會(huì)被呼叫。 Cup.m 里的 CupOverflowException 是一個(gè) NSString 常數(shù)物件。在Objective-C 中, 符號(hào)通常用來(lái)代表這是語(yǔ)言的衍生部分。C 語(yǔ)言形式的字符串(C string)就像 C/C+ 一樣是 String constant 的形式,型別為 char *。繼承、多型(Inheritance, Polymorphism)以及其他面向?qū)ο蠊δ躨d 型別 Objective-C 有種叫做 id 的型別,它的運(yùn)作有時(shí)候像是 void*,不過(guò)它卻嚴(yán)格規(guī)定只能用在對(duì)象。Objective-C 與 Java

40、 跟 C+ 不一樣,你在呼叫一個(gè)對(duì)象的method 時(shí),并不需要知道這個(gè)對(duì)象的型別。當(dāng)然這個(gè) method 一定要存在,這稱為 Objective-C 的訊息傳遞。 基于 Programming in Objective-C, Copyright 2004 by Sams Publishing一書中的范例,并經(jīng)過(guò)允許而刊載。 #import interface Fraction: NSObject int numerator; int denominator; -(Fraction*) initWithNumerator: (int) n denominator: (int) d; -(voi

41、d) print; -(void) setNumerator: (int) d; -(void) setDenominator: (int) d; -(void) setNumerator: (int) n andDenominator: (int) d; -(int) numerator; -(int) denominator;end o #import Fraction.h #import implementation Fraction -(Fraction*) initWithNumerator: (int) n denominator: (int) d self = super ini

42、t; if ( self ) self setNumerator: n andDenominator: d; return self; -(void) print printf( %i / %i, numerator, denominator ); -(void) setNumerator: (int) n numerator = n; -(void) setDenominator: (int) d denominator = d; -(void) setNumerator: (int) n andDenominator: (int) d numerator = n; denominator

43、= d; -(int) denominator return denominator; -(int) numerator return numerator; end o #import interface Complex: NSObject double real; double imaginary; -(Complex*) initWithReal: (double) r andImaginary: (double) i; -(void) setReal: (double) r; -(void) setImaginary: (double) i; -(void) setReal: (double) r andImaginary: (double) i; -(double) real; -(double) imaginary; -(void) print; end o #import Complex.h #import implementation Complex -(Complex*) initWithReal: (double) r andImaginary: (double) i self = super init; if ( self ) self setReal: r andImaginary: i; return self; -(void) setRea

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論