在 Objective-C 的學習路徑上,當你熟悉了基本的語法與物件導向概念之後,還有一批「進階特性」值得深入掌握。它們包括包裝類、description 方法、類別(Category)、擴展(Extension)、協議與委託、異常處理,以及運行時反射機制。本文將依序梳理這些主題,並搭配可執行的範例,幫助你建立完整的知識地圖。
Objective-C 中的基本資料型別(如 int、float、char)並不是物件,無法直接放進只接受物件的集合類(例如 NSArray、NSDictionary)。這時就需要「包裝類」把基本型別轉換成物件。
NSValue 是通用包裝類,可以包裝 short、int、long、float、char、id、指標等各種類型的單一數值。
NSNumber 則專門用來包裝 C 語言的純量資料型別,是最常使用的包裝類。
NSNumber 的常用方法可以歸納為三類:
-- + numberWithXxx: 將指定型別的值包裝成 NSNumber 物件;
-- - initWithXxx: 先建立 NSNumber 物件,再用基本型別的值進行初始化;
-- - xxxValue: 取出 NSNumber 所包裝的基本型別數值。
/************************************************************************* > File Name: OCNSNumberDemo.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 六 10/ 3 12:50:15 2015 ************************************************************************/ #importint main(int argc, char * argv[]) { @autoreleasepool { NSNumber * num_int = [NSNumber numberWithInt : 10]; NSNumber * num_double = [NSNumber numberWithDouble : 10]; NSNumber * num_char = [NSNumber numberWithChar : 'A']; NSLog(@number_int : %d, number_double : %g, num_char : %c, [num_int intValue], [num_double doubleValue], [num_char charValue]); NSNumber * num_int1 = [[NSNumber alloc] initWithInt : 10]; NSNumber * num_double1 = [[NSNumber alloc] initWithDouble : 10]; NSNumber * num_char1 = [[NSNumber alloc] initWithChar : 'A']; NSLog(@number_int1 : %d, number_double1 : %g, num_char1 : %c, [num_int1 intValue], [num_double1 doubleValue], [num_char1 charValue]); } }
執行結果:
localhost:oc_object octopus$ clang -fobjc-arc -framework Foundation OCNSNumberDemo.m localhost:oc_object octopus$ ./a.out 2015-10-03 13:00:46.465 a.out[887:507] number_int : 10, number_double : 10, num_char : A 2015-10-03 13:00:46.468 a.out[887:507] number_int1 : 10, number_double1 : 10, num_char1 : A
description 方法相當於 Java 中 Object 的 toString(),用來回傳物件「長什麼樣子」的字串描述。
-- 來源:description 定義於 NSObject,因此所有物件都擁有這個方法;
-- 預設行為:預設會回傳「類名: 記憶體位址」的格式;
-- 輸出機制:當你使用 NSLog() 印出一個物件時,實際印出的就是該物件的 description 回傳值;
-- 等價關係:對於 person 物件,印出 [person description] 與直接印出 person 的結果完全相同。
/************************************************************************* > File Name: OCDescriptionDemo.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 六 10/ 3 14:25:28 2015 ************************************************************************/ #import@interface OCDescriptionDemo : NSObject @property (nonatomic, copy) NSString * name; @property (nonatomic, assign) int age; - (id) initWithNameAndAge : (NSString *) set_name setAge : (int) set_age; @end @implementation OCDescriptionDemo @synthesize name; @synthesize age; - (id) initWithNameAndAge : (NSString *) set_name setAge : (int) set_age { self.name = set_name; self.age = set_age; return self; } - (NSString *) description { NSString * des = [NSString stringWithFormat : @ , self.name, self.age]; return des; } @end int main(int argc, char * argv[]) { @autoreleasepool { OCDescriptionDemo * description = [[OCDescriptionDemo alloc] initWithNameAndAge : @Tom setAge : 18]; NSLog(@%@, description); } }
執行結果:
localhost:oc_object octopus$ clang -fobjc-arc -framework Foundation OCDescriptionDemo.m localhost:oc_object octopus$ ./a.out 2015-10-03 14:50:18.665 a.out[970:507]
-- 作用:判斷兩個變量是否相等;
-- 前提:僅適用於基本型別的比較,兩個值相等時回傳 true。對於指標型別,== 比較的是「記憶體位址」,通常沒有實際意義。
-- 作用:確保相同的字串常量在記憶體中只存在一份,不會產生多個重複的副本;
-- 例外:以 [NSString stringWithFormat:] 動態產生的字串不會被放進常量池。
-- 來源:isEqual: 是 NSObject 提供的實例方法,用於判斷兩個同類型的物件是否相等;
-- 預設行為:預設仍是比較位址,因此需要開發者自行覆寫;
-- NSString 的實作:NSString 覆寫了 isEqual:,只要字串內容相同即回傳 true;
-- isEqualToString::NSString 專用的方法,用來判斷兩個字串的字符序列是否一致。
覆寫 isEqual: 時,必須滿足以下五項約定:
-- 自反性:對任意物件 x,[x isEqual: x] 必須回傳 true;
-- 對稱性:對 x 與 y,[x isEqual: y] 與 [y isEqual: x] 的結果必須相同;
-- 傳遞性:若 [x isEqual: y] 與 [y isEqual: z] 皆為 true,則 x 與 z 也必須相等;
-- 一致性:只要物件未被修改,多次呼叫的結果應保持一致;
-- nil 比較:若 x 不為 nil,則 [x isEqual: nil] 必須回傳 false。
/************************************************************************* > File Name: OCEqual.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 六 10/ 3 16:07:56 2015 ************************************************************************/ #import@interface OCEqual : NSObject @property (nonatomic, copy) NSString * name; @property (nonatomic, assign) int age; - (id) initWithName : (NSString *) set_name setAge : (int) set_age; @end @implementation OCEqual @synthesize name; @synthesize age; - (id) initWithName : (NSString *) set_name setAge : (int) set_age { self.name = set_name; self.age = set_age; return self; } - (BOOL) isEqual : (id) other { if(self == other) return YES; if(other != nil && [other isMemberOfClass : OCEqual.class]) { OCEqual * equal = (OCEqual *) other; return [self.name isEqual : equal.name] && (self.age == equal.age); } return NO; } @end int main(int argc, char * argv[]) { @autoreleasepool { int int_a = 10; int double_a = 10.0; NSLog(@int_a == double_a : %d, (int_a == double_a)); NSString * str_a = @Octopus; NSString * str_b = @Octopus; NSString * str_c = [NSString stringWithFormat : @Octopus]; NSString * str_d = [NSString stringWithFormat : @Octopus]; NSLog(@str_a == str_b : %d, str_c == str_d : %d, [str_c isEqual : str_d] : %d, str_a == str_b, str_c == str_d, [str_c isEqual : str_d]); OCEqual * equal_a = [[OCEqual alloc] initWithName : @Tom setAge : 18]; OCEqual * equal_b = [[OCEqual alloc] initWithName : @Jerry setAge : 20]; OCEqual * equal_c = [[OCEqual alloc] initWithName : @Jerry setAge : 20]; NSLog(@[equal_a isEqual : equal_b] : %d, [equal_b isEqual : equal_c] : %d, [equal_a isEqual : equal_b], [equal_b isEqual : equal_c]); } }
執行結果:
localhost:oc_object octopus$ clang -fobjc-arc -framework Foundation OCEqual.m localhost:oc_object octopus$ ./a.out 2015-10-03 16:58:35.690 a.out[1168:507] int_a == double_a : 1 2015-10-03 16:58:35.693 a.out[1168:507] str_a == str_b : 1, str_c == str_d : 0, [str_c isEqual : str_d] : 1 2015-10-03 16:58:35.693 a.out[1168:507] [equal_a isEqual : equal_b] : 0, [equal_b isEqual : equal_c] : 1
開發過程中,我們往往需要為既有的類添加新的行為。若使用繼承,子類可以在父類基礎上新增或覆寫方法;但問題在於——如果我們想「為父類本身」添加一個方法,透過繼承就無法直接達成,因為你無法回頭修改父類的原始碼。
在 Objective-C 中沒有介面(interface)的概念,當需要類似介面的能力時,通常會定義一個父類並派生多個子類,這一組相關的類被稱為「類簇」。要為整個類簇添加方法,最直接的做法就是擴展類簇中的父類——而 Category 正是實現這件事的利器。
-- 作用:為現有的類添加方法,無需存取原始碼,也不必建立子類;
-- 優點:能動態地為現有類擴充方法,並將類的定義模組化地分散到多個檔案中。
-- 檔案命名:介面檔採「類名+類別名.h」的命名方式。例如要擴展 OCPerson,類別名為 SB,則檔案名為 OCPerson+SB.h;
@interface 已有類 (類別名) //方法定義 ... @end
-- 類別名:括號中的類別名只要是專案內獨一無二即可,而 @interface 後面的必須是「已存在的類」;
-- 圓括號:類別名緊跟在要擴展的類之後,並以圓括號包住;
-- 定義內容:類別中通常只定義方法,不定義實例變量。
-- 檔案命名:實作檔採「類名+類別名.m」的命名方式,例如 OCPerson+SB.m;
@implementation 已有類 (類別名) //方法定義 ... @end
-- 影響範圍:透過 category 添加的方法會作用於被擴展的類,同時也會影響它的所有子類;
-- 多重類別:一個類可以對應多個類別,各自為類添加不同的方法;
-- 主要用途:模組化設計、呼叫私有方法,以及實現非正式協議。
以下為 NSNumber 添加一個計算圓面積的方法:
-- NSNumber+SB.h:
/************************************************************************* > File Name: NSNumber+SB.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 六 10/ 3 18:58:53 2015 ************************************************************************/ #import@interface NSNumber (SB) - (NSNumber *) circleAera : (double) radius; @end
-- NSNumber+SB.m:
/************************************************************************* > File Name: NSNumber+SB.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 六 10/ 3 19:02:05 2015 ************************************************************************/ #import NSNumber+SB.h @implementation NSNumber (SB) - (NSNumber *) circleAera : (double) radius { double aera = 3.1415926 * radius * radius; return [NSNumber numberWithDouble : aera]; } @end
-- NSNumber+SBTest.m:
/************************************************************************* > File Name: NSNumber+SBTest.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 六 10/ 3 19:08:19 2015 ************************************************************************/ #import#import NSNumber+SB.h int main(int argc, char * argv[]) { @autoreleasepool { NSNumber * num = [NSNumber numberWithInt : 3]; NSNumber * circleAera = [num circleAera : 1]; NSLog(@%@, circleAera); } }
-- 執行結果:
localhost:oc_object octopus$ clang -fobjc-arc -framework Foundation NSNumber+SB.m NSNumber+SBTest.m localhost:oc_object octopus$ ./a.out 2015-10-03 19:18:13.625 a.out[1333:507] 3.1415926
-- 實現唯一的限制:一個類的介面定義在 類名.h,實作定義在 類名.m,無法把實作拆到多個 .m 檔中;
-- 檔案肥大問題:當類別規模龐大時,把全部程式碼塞進同一個 .m 檔會極難維護。此時 Category 就能派上用場,把不同職責的實作拆分到各自的檔案裡。
-- 私有方法:只在實作檔中定義、未在介面檔中宣告的方法,不允許外部直接呼叫;
-- 呼叫方式:可以透過 category 把私有方法「公開」出來。此外,也能使用 NSObject 的 performSelector: 來呼叫,但這種方式會繞過語法檢查,可能埋下未知風險。
-- OCPrivate.h:
/************************************************************************* > File Name: OCPrivate.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 日 10/ 4 06:55:34 2015 ************************************************************************/ #import@interface OCPrivate : NSObject @property (nonatomic, copy) NSString * name; -(void) info; @end
-- OCPrivate.m:
/************************************************************************* > File Name: OCPrivate.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 日 10/ 4 06:57:48 2015 ************************************************************************/ #import OCPrivate.h @implementation OCPrivate @synthesize name; - (void) info { NSLog(@name : %@, self.name); } - (void) speak { NSLog(@Hello World !); } @end
-- OCPrivate+SB.h:
/************************************************************************* > File Name: OCPrivate+SB.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 日 10/ 4 07:19:35 2015 ************************************************************************/ #import OCPrivate.h @interface OCPrivate (SB) - (void) speak; @end
-- OCPrivateTest.m:
/************************************************************************* > File Name: OCPrivateTest.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 日 10/ 4 07:22:04 2015 ************************************************************************/ #import OCPrivate+SB.h int main(int argc, char * argv[]) { @autoreleasepool { OCPrivate * priva = [[OCPrivate alloc] init]; priva.name = @Tom; [priva info]; [priva speak]; } }
-- 本質:Extension(類擴展)可以理解為「匿名類別」,其語法如下:
@interface 已有類 () { //實例變量 ... } // 方法定義 ... @end
-- 常見用法:定義兩個頭檔 OCExtension.h 與 OCExtension+speak.h,並在 OCExtension.m 中導入 OCExtension+speak.h。Extension 通常用來宣告私有屬性與私有方法。
-- OCExtension.h:
/************************************************************************* > File Name: OCExtension.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 日 10/ 4 08:18:43 2015 ************************************************************************/ #import@interface OCExtension : NSObject @property (nonatomic, copy) NSString * name; @property (nonatomic, assign) int age; - (void) info; @end
-- OCExtension+speak.h:
/************************************************************************* > File Name: OCExtension+speak.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 日 10/ 4 08:31:37 2015 ************************************************************************/ #import OCExtension.h @interface OCExtension () @property (nonatomic, copy) NSString * home; - (void) speak : (NSString *) content; @end
-- OCExtension.m:
/************************************************************************* > File Name: OCExtension.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 日 10/ 4 08:27:50 2015 ************************************************************************/ #import OCExtension+speak.h @implementation OCExtension @synthesize name; @synthesize age; @synthesize home; - (void) info { NSLog(@info : name : %@ , age : %d, self.name, self.age); } - (void) speak : (NSString *) content { NSLog(@%@ speak %@, self.name, content); } @end
-- OCExtensionTest.m:
/************************************************************************* > File Name: OCExtensionTest.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 日 10/ 4 13:20:42 2015 ************************************************************************/ #import OCExtension+speak.h int main(int argc, char * argv[]) { @autoreleasepool { OCExtension * extension = [[OCExtension alloc] init]; extension.name = @Tom; extension.age = 18; extension.home = @China; [extension info]; [extension speak : @Are you kidding me]; } }
-- 協議的作用:Objective-C 的協議相當於其他語言中的介面,它定義了一組多個類共享的行為規範,通常是一批沒有實作的公用方法,交由各個類自行實作。
-- 非正式協議:以 NSObject 為基礎建立一個類別,在該類別中宣告新增方法,等於為所有繼承自 NSObject 的子類都加上這些方法。實作時,再由各子類去實作這些方法。
-- NSObject+speak.h:為 NSObject 定義的類別介面,所有繼承 NSObject 的類都應實作其中的抽象方法;
/************************************************************************* > File Name: NSObject+speak.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 08:55:48 2015 ************************************************************************/ #import@interface NSObject (speak) - (void) speak; @end
-- OCNSObjectProtocal.h:NSObject 子類的介面,需導入 NSObject+speak.h;
/************************************************************************* > File Name: OCNSObjectProtocal.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 09:00:37 2015 ************************************************************************/ #import NSObject+speak.h @interface OCNSObjectProtocal : NSObject @end
-- OCNSObjectProtocal.m:必須實作類別中定義的 speak 方法;
/************************************************************************* > File Name: OCNSObjectProtocal.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 09:02:03 2015 ************************************************************************/ #import OCNSObjectProtocal.h @implementation OCNSObjectProtocal - (void) speak { NSLog(@Speak Hello World); } @end
-- OCNSObjectProtocalTest.m:測試類;
/************************************************************************* > File Name: OCNSObjectProtocalTest.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 09:04:31 2015 ************************************************************************/ #import OCNSObjectProtocal.h int main(int argc, char * argv[]) { @autoreleasepool { OCNSObjectProtocal * obj = [[OCNSObjectProtocal alloc] init]; [obj speak]; } }
-- 執行結果:
bogon:oc_object octopus$ clang -fobjc-arc -framework Foundation OCNSObjectProtocal.m OCNSObjectProtocalTest.m bogon:oc_object octopus$ ./a.out 2015-10-05 09:06:44.895 a.out[2100:507] Speak Hello World
@protocol 協議名稱 <父類協議1, 父類協議2 ...> // N 個協議方法 @end
-- 命名規範:採用與類名相同的命名風格;
-- 繼承規則:一個協議可以有多個父類協議,但協議只能繼承協議,不能繼承類;
-- 方法規則:協議中只能定義抽象方法(不能實作),既可定義類方法,也可定義實例方法。
@interface 類名 : 父類 <協議1, 協議2...>
-- 對應關係:一個類可以同時實現多個協議。
-- 用原類別宣告:形如 OCCat * cat;
-- 用協議宣告:形如 NSObject <協議1, 協議2 ...> * cat;
-- 用 id 宣告:形如 id<協議名稱> cat,注意此處不帶星號指標標識。
-- OCAnimalProtocol.h:最基礎的協議之一;
/************************************************************************* > File Name: OCAnimalProtocol.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 09:25:41 2015 ************************************************************************/ #import@protocol OCAnimalProtocol - (void) name; - (void) age; @end
-- OCProtocolBord.h:另一個基礎協議;
/************************************************************************* > File Name: OCProtocolBord.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 09:40:08 2015 ************************************************************************/ #import@protocol OCProtocolBord - (void) fly; @end
-- OCProtocolCat.h:繼承上述兩個協議的協議;
/************************************************************************* > File Name: OCProtocolCat.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 09:45:17 2015 ************************************************************************/ #import#import OCAnimalProtocol.h #import OCProtocolBord.h @protocol OCProtocolCat - (void) purr; @end
-- OCCat.h:宣告 OCCat 實現 OCProtocolCat 協議;
/************************************************************************* > File Name: OCCat.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 09:50:21 2015 ************************************************************************/ #import OCProtocolCat.h @interface OCCat : NSObject@end
-- OCCat.m:OCCat 的實作;
/************************************************************************* > File Name: OCCat.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 09:52:45 2015 ************************************************************************/ #import OCCat.h @implementation OCCat - (void) name { NSLog(@name : cat); } - (void) age { NSLog(@age : 18); } - (void) fly { NSLog(@cat fly); } - (void) purr { NSLog(@cat purr); } @end
-- OCProtocolTest.m:功能測試類;
/************************************************************************* > File Name: OCProtocolTest.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 10:14:38 2015 ************************************************************************/ #import#import OCCat.h int main(int argc, char * argv[]) { @autoreleasepool { OCCat * cat = [[OCCat alloc] init]; [cat name]; [cat age]; [cat fly]; [cat purr]; NSObject * cat1 = [[OCCat alloc] init]; [cat1 name]; [cat1 age]; [cat1 fly]; [cat1 purr]; id cat2 = [[OCCat alloc] init]; [cat2 name]; [cat2 age]; } }
-- 執行結果:
bogon:6.4 octopus$ clang -fobjc-arc -framework Foundation OCCat.m OCProtocolTest.m bogon:6.4 octopus$ ./a.out 2015-10-05 10:24:20.099 a.out[2271:507] name : cat 2015-10-05 10:24:20.101 a.out[2271:507] age : 18 2015-10-05 10:24:20.102 a.out[2271:507] cat fly 2015-10-05 10:24:20.102 a.out[2271:507] cat purr 2015-10-05 10:24:20.102 a.out[2271:507] name : cat 2015-10-05 10:24:20.103 a.out[2271:507] age : 18 2015-10-05 10:24:20.103 a.out[2271:507] cat fly 2015-10-05 10:24:20.104 a.out[2271:507] cat purr 2015-10-05 10:24:20.104 a.out[2271:507] name : cat 2015-10-05 10:24:20.104 a.out[2271:507] age : 18
委託的核心概念:定義協議的類,把「定義協議的方法」的實作責任委託給「實現協議的類」。這樣做的好處是讓類具備更好的通用性——具體動作交給實作類去完成,而不必依賴特定對象。
建立 Xcode 工程:
-- 歡迎畫面選擇「Create a new xcode project」:

-- 建立一個 OS X 下的 Cocoa Application:

-- 完成工程建立:

工程中的原始檔:
-- main.m:main() 函數入口;
-- OCAppDelegate.h:OCAppDelegate 類的介面檔;
-- OCAppDelegate.m:OCAppDelegate 類的實作檔。

範例程式碼:
-- 前置操作:刪除 MainMenu.xib 檔,並移除 Hello-Info.plist 中的 MainMenu 選項;

-- OCAppDelegate.h:
// // OCAppDelegate.h // Hello // // Created by octopus on 15-10-5. // Copyright (c) 2015年 www.octopus.org.cn. All rights reserved. // #import//該接口 實現 NSApplicationDelegate 協議 @interface OCAppDelegate : NSObject //定義窗口 @property (strong) NSWindow *window; @end
-- OCAppDelegate.m:
// // OCAppDelegate.m // Hello // // Created by octopus on 15-10-5. // Copyright (c) 2015年 www.octopus.org.cn. All rights reserved. // #import OCAppDelegate.h @implementation OCAppDelegate @synthesize window; //應用加載完成時回調的方法 - (void)applicationWillFinishLaunching:(NSNotification *)notification { //設置窗口屬性 self.window = [[NSWindow alloc] initWithContentRect : NSMakeRect(300, 300, 320, 200) styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |NSClosableWindowMask) backing:NSBackingStoreBuffered defer:NO]; self.window.title = @Hello World; //設置文本框屬性 NSTextField * label = [[NSTextField alloc] initWithFrame:NSMakeRect(60, 120, 200, 60)]; [label setSelectable:YES]; [label setBezeled:YES]; [label setDrawsBackground:YES]; [label setStringValue:@HELLO WORLD]; //設置按鈕屬性 NSButton * button = [[NSButton alloc] initWithFrame:NSMakeRect(120, 40, 80, 30)]; button.title = @OCTOPUS; [button setBezelStyle:NSRoundedBezelStyle]; [button setBounds:NSMakeRect(120, 40, 80, 30)]; //將 文本框 和 按鈕 添加到窗口中 [self.window.contentView addSubview:label]; [self.window.contentView addSubview:button]; } //加載完成時回調的方法 - (void) applicationDidFinishLaunching:(NSNotification *)notification { //顯示窗口 [self.window makeKeyAndOrderFront:self]; } @end
-- main.m:
// // main.m // Hello // // Created by octopus on 15-10-5. // Copyright (c) 2015年 www.octopus.org.cn. All rights reserved. // #import#import OCAppDelegate.h int main(int argc, const char * argv[]) { @autoreleasepool { //創建一個實現了 NSApplicationDelegate 協議的對象 OCAppDelegate * delegate = [[OCAppDelegate alloc] init]; //獲取 NSApplication 單例對象 [NSApplication sharedApplication]; //設置代理, 將處理方法委托給 delegate [NSApp setDelegate : delegate]; //開始運行程序 return NSApplicationMain(argc, argv); } }
-- 運行結果:

-- 作用:把可能引發異常的程式碼放進 @try 區塊,當程式出錯時,由 @catch 區塊負責捕捉與處理;
-- 各區塊職責:@try 存放可能出錯的程式碼,@catch 撰寫異常處理邏輯,@finally 負責回收資源;
@try { // 業務邏輯 } @catch (異常類型名1 ex) { //異常處理代碼 } @catch (異常類型名2 ex) { //異常處理代碼 } // 可以捕捉 N 個 異常 ... @finally { //回收資源 }
-- 產生異常物件:@try 中若發生異常,系統會建立一個異常物件並拋出;
-- 尋找處理者:執行環境收到異常物件後,若有能處理它的 @catch,就交給該 @catch 處理(即捕獲);若無任何 @catch 能處理,程式將終止;
-- @catch 的匹配順序:執行環境會依序判斷異常物件的型別是否為各 @catch 所宣告型別(或其子類),一旦匹配成功即由該 @catch 接手,否則繼續比對下一個;
-- 取得異常資訊:系統會把異常物件傳給 @catch 的形參,透過該形參即可讀取詳細資訊。
其他重點:
-- 對應關係:一個 @try 可以對應多個 @catch;
-- 花括號不可省略:@try、@catch、@finally 的大括號一律不能省略。
NSException 異常類:
-- 地位:NSException 是 Objective-C 中所有異常的父類;
-- 位置擺放:由於 @catch 會比對「型別或其子類」,若把 NSException 放在最前面,後續更專屬的 @catch 將永遠無法被觸發,因此它必須放在最後。
-- name:回傳異常的詳細名稱;
-- reason:回傳引發異常的原因;
-- userInfo:回傳伴隨異常的使用者資訊,型別為 NSDictionary。
若在 @try 中開啟了實體資源(資料庫、網路連線、檔案等),都必須妥善回收,而 @finally 是最合適的位置。
-- 為什麼放 finally:若放在 @try 末尾回收,一旦中途出錯,後面的回收程式碼就無法執行;若放在 @catch 中回收,當沒有異常發生時又不會執行。@finally 是無論如何都會執行的區塊,因此在此回收最為可靠。
-- OCAnimal.h:定義協議;
/************************************************************************* > File Name: OCAnimal.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 16:30:02 2015 ************************************************************************/ #import@protocol OCAnimal @optional - (void) run; @end
-- OCCat.h:OCCat 的介面;
/************************************************************************* > File Name: OCCat.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 16:33:59 2015 ************************************************************************/ #import OCAnimal.h @interface OCCat : NSObject@end
-- OCCat.m:OCCat 的實作;
/************************************************************************* > File Name: OCCat.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 16:36:36 2015 ************************************************************************/ #import OCCat.h @implementation OCCat @end
-- OCCatTest.m:測試類(未捕捉異常);
/************************************************************************* > File Name: OCCatTest.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 16:38:01 2015 ************************************************************************/ #import OCCat.h int main(int argc, char * argv[]) { @autoreleasepool { OCCat * cat = [[OCCat alloc] init]; [cat run]; } }
-- 執行結果(未捕捉時程式崩潰):
bogon:6.5 octopus$ clang -fobjc-arc -framework Foundation OCCat.m OCCatTest.m bogon:6.5 octopus$ ./a.out 2015-10-05 16:39:23.589 a.out[2985:507] -[OCCat run]: unrecognized selector sent to instance 0x7fd7a3401870 2015-10-05 16:39:23.611 a.out[2985:507] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[OCCat run]: unrecognized selector sent to instance 0x7fd7a3401870' *** First throw call stack: ( 0 CoreFoundation 0x00007fff903dd25c __exceptionPreprocess + 172 1 libobjc.A.dylib 0x00007fff8ecdbe75 objc_exception_throw + 43 2 CoreFoundation 0x00007fff903e012d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205 3 CoreFoundation 0x00007fff9033b044 ___forwarding___ + 452 4 CoreFoundation 0x00007fff9033adf8 _CF_forwarding_prep_0 + 120 5 a.out 0x0000000108575efd main + 109 6 libdyld.dylib 0x00007fff851f35fd start + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException Abort trap: 6
-- OCCatTest.m:加入異常捕捉後的版本;
/************************************************************************* > File Name: OCCatTest.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 16:38:01 2015 ************************************************************************/ #import OCCat.h int main(int argc, char * argv[]) { @autoreleasepool { @try { OCCat * cat = [[OCCat alloc] init]; [cat run]; } @catch (NSException * ex) { NSLog(@exception name : %@, reason : %@, ex.name, ex.reason); } @finally { NSLog(@finally execute); } NSLog(@success); } }
-- 執行結果:
bogon:6.5 octopus$ clang -fobjc-arc -framework Foundation OCCat.m OCCatTest.m bogon:6.5 octopus$ ./a.out 2015-10-05 16:53:46.850 a.out[3008:507] -[OCCat run]: unrecognized selector sent to instance 0x7f884bc018b0 2015-10-05 16:53:46.853 a.out[3008:507] exception name : NSInvalidArgumentException, reason : -[OCCat run]: unrecognized selector sent to instance 0x7f884bc018b0 2015-10-05 16:53:46.853 a.out[3008:507] finally execute 2015-10-05 16:53:46.854 a.out[3008:507] success
@throw 異常對象;
-- OCException.h:介面;
/************************************************************************* > File Name: OCException.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 16:58:24 2015 ************************************************************************/ #import@interface OCException : NSException @end
-- OCException.m:實作;
/************************************************************************* > File Name: OCException.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 17:03:15 2015 ************************************************************************/ #import OCException.h @implementation OCException @end
-- OCCatTest.m:拋出自訂異常的測試類;
/************************************************************************* > File Name: OCCatTest.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 16:38:01 2015 ************************************************************************/ #import OCException.h int main(int argc, char * argv[]) { @autoreleasepool { @throw [[OCException alloc] initWithName : @OCException reason : @this reason is imporant userInfo : nil]; } }
-- 執行結果:
bogon:6.5 octopus$ clang -fobjc-arc -framework Foundation OCException.m OCCatTest.m bogon:6.5 octopus$ ./a.out 2015-10-05 17:04:12.432 a.out[3040:507] *** Terminating app due to uncaught exception 'OCException', reason: 'this reason is imporant' *** First throw call stack: ( 0 CoreFoundation 0x00007fff903dd25c __exceptionPreprocess + 172 1 libobjc.A.dylib 0x00007fff8ecdbe75 objc_exception_throw + 43 2 a.out 0x00000001062abef7 main + 135 3 libdyld.dylib 0x00007fff851f35fd start + 1 ) libc++abi.dylib: terminating with uncaught exception of type OCException Abort trap: 6
-- 透過 OC 原始碼:撰寫 OC 原始碼,交由編譯器編譯後執行;
-- 透過 NSObject 動態編程:NSObject 是所有類的基類,任何物件都能直接呼叫 NSObject 的方法;
-- 呼叫執行期(Runtime)函數:執行期系統以動態庫形式存在,可直接呼叫這些函數進行動態編程。
-- 用類名:呼叫 Class NSClassFromString(NSString * aClassName),傳入類名字串;
-- 用 class 類方法:呼叫 [NSString class];
-- 用 class 物件方法:呼叫 [@hello class];
-- 推薦第二種:寫法更安全,編譯階段即可檢查類是否存在,效能也較佳。
/************************************************************************* > File Name: OCGetClass.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 23:31:51 2015 ************************************************************************/ #importint main(int argc, char * argv[]) { @autoreleasepool { //通過 NSClassFromString 方法傳入 類名字符串 獲取 Class 對象 Class clazz = NSClassFromString(@NSDate); NSLog(@%@, clazz); id date = [[clazz alloc] init]; NSLog(@date : %@, date); NSString * str = @hello; // 通過調用 類 或 對象的 class 方法 NSLog(@[str class] : %@, [NSString class] : %@, [str class], [NSString class]); // 通過調用 類 或 對象的 getter 方法獲取, 即用 . 方法獲取 NSLog(@str.class : %@, NSString.class : %@, str.class, NSString.class); } }
-- 執行結果:
bogon:6.6 octopus$ clang -fobjc-arc -framework Foundation OCGetClass.m bogon:6.6 octopus$ ./a.out 2015-10-05 23:39:28.692 a.out[3237:507] NSDate 2015-10-05 23:39:28.699 a.out[3237:507] date : 2015-10-05 15:39:28 +0000 2015-10-05 23:39:28.700 a.out[3237:507] [str class] : __NSCFConstantString, [NSString class] : NSString 2015-10-05 23:39:28.700 a.out[3237:507] str.class : __NSCFConstantString, NSString.class : NSString
-- 判斷是否為確切類別:isMemberOfClass:,傳入 Class 物件,判斷該物件是否為該類的「直接」實例;
-- 判斷是否為該類或其子類:isKindOfClass:,傳入 Class 物件,判斷該物件是否為該類或其子類的實例;
-- 判斷是否實現協議:conformsToProtocol:,傳入 Protocol 參數,可透過 @protocol(協議名稱) 或 NSProtocolFromString(協議名稱字串) 取得。
-- OCAnimal.h:定義協議;
/************************************************************************* > File Name: OCAnimal.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 23:54:14 2015 ************************************************************************/ #import@protocol OCAnimal - (void) name; @end
-- OCCat.h:定義介面;
/************************************************************************* > File Name: OCCat.h > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 23:56:16 2015 ************************************************************************/ #import OCAnimal.h @interface OCCat : NSObject@end
-- OCCat.m:定義實作;
/************************************************************************* > File Name: OCCat.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 一 10/ 5 23:58:47 2015 ************************************************************************/ #import OCCat.h @implementation OCCat - (void) name { NSLog(@My name is Tom); } @end
-- OCCatMain.m:測試類;
/************************************************************************* > File Name: OCCatMain.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 二 10/ 6 00:00:01 2015 ************************************************************************/ #import OCCat.h int main(int argc, char * argv[]) { @autoreleasepool { OCCat * cat = [[OCCat alloc] init]; NSLog(@%@, cat.class); NSLog(@cat isMemberOfClass OCCat : %d, [cat isMemberOfClass : OCCat.class]); NSLog(@cat isMemberOfClass NSObject : %d, [cat isMemberOfClass : NSObject.class]); NSLog(@cat isKindOfClass OCCat : %d, [cat isKindOfClass : OCCat.class]); NSLog(@cat isKindOfClass OCCat : %d, [cat isKindOfClass : NSObject.class]); NSLog(@cat conformsToProtocol OCAnimal : %d, [cat conformsToProtocol : @protocol(OCAnimal)]); } }
-- 執行結果:
bogon:6.6 octopus$ clang -fobjc-arc -framework Foundation OCCat.m OCCatMain.m bogon:6.6 octopus$ ./a.out 2015-10-06 00:07:56.838 a.out[3337:507] OCCat 2015-10-06 00:07:56.840 a.out[3337:507] cat isMemberOfClass OCCat : 1 2015-10-06 00:07:56.840 a.out[3337:507] cat isMemberOfClass NSObject : 0 2015-10-06 00:07:56.841 a.out[3337:507] cat isKindOfClass OCCat : 1 2015-10-06 00:07:56.841 a.out[3337:507] cat isKindOfClass OCCat : 1 2015-10-06 00:07:56.842 a.out[3337:507] cat conformsToProtocol OCAnimal : 1
KVC(Key-Value Coding)機制能動態呼叫物件的 getter 與 setter 方法。無論變量定義在介面還是實作中,也無論使用何種存取控制(private 或 public),都能透過 KVC 存取。
NSObject 提供了 respondsToSelector: 方法,傳入代表方法的 SEL 參數,若可呼叫則回傳 YES,否則回傳 NO。
取得 SEL 物件的兩種方式:
-- @selector 指令:傳入完整的方法簽名關鍵字(僅有方法名並不足夠);
@selector(setAge:)
-- NSSelectorFromString 函數:依方法簽名關鍵字字串取得對應方法。
NSSelectorFromString(@setAge:)
-- 方式一:使用 NSObject 的 performSelector:,傳入 SEL 物件,並以 withObject: 傳遞參數;
[student performSelector : @selector(setAge:) withObject : [NSNumber numberWithInt : 18]]; [student performSelector : NSSelectorFromString(@setAge:) withObject : [NSNumber numberWithInt : 19]];
-- 方式二:使用 objc_msgSend(receiver, selector, ...),第一個參數是呼叫者,第二個是方法,其餘為方法參數;
objc_msgSend (student, @selector(setAge:), [NSNumber numberWithInt : 20]); objc_msgSend (student, NSSelectorFromString(@setAge:), [NSNumber numberWithInt : 21]);
-- 注意:使用第二種方式需導入 #import <objc/message.h>;回傳浮點數時改用 objc_msgSend_fpret(),回傳結構體時改用 objc_msgSend_stret()。
-- 取得 IMP:NSObject 提供了 - (IMP)methodForSelector:(SEL)aSelector,傳入 SEL 並回傳 IMP 物件;
-- IMP 的意義:IMP 是 Objective-C 方法的函數指標變量,代表函數入口,透過 IMP 也能呼叫函數;
-- 呼叫語法:以「回傳型別 (*指標變量)(id, SEL, ...)」的形式宣告,第一個參數是呼叫者,第二個是 SEL 物件,其後為方法參數。
-- OCStudent.m:介面、實作與主函數合一;
/************************************************************************* > File Name: OCStudent.m > Author: octopus > Mail: octopus_truth.163.com > Created Time: 二 10/ 6 11:19:49 2015 ************************************************************************/ #import#import @interface OCStudent : NSObject @end @implementation OCStudent - (void) setAge : (NSNumber *) age { int age_num = [age intValue]; NSLog(@age is : %d, age_num); } @end int main(int argc, char * argv[]) { @autoreleasepool { OCStudent * student = [[OCStudent alloc] init]; [student performSelector : @selector(setAge:) withObject : [NSNumber numberWithInt : 18]]; [student performSelector : NSSelectorFromString(@setAge:) withObject : [NSNumber numberWithInt : 19]]; objc_msgSend (student, @selector(setAge:), [NSNumber numberWithInt : 20]); objc_msgSend (student, NSSelectorFromString(@setAge:), [NSNumber numberWithInt : 21]); } }
-- 執行結果(會出現 ARC 相關警告,但可正常執行):
bogon:6.6 octopus$ clang -fobjc-arc -framework Foundation OCStudent.m OCStudent.m:29:12: warning: performSelector may cause a leak because its selector is unknown [-Warc-performSelector-leaks] [student performSelector : NSSelectorFromString(@setAge:) withObject : [NSNumber numberWithInt : 19]]; ^ OCStudent.m:29:30: note: used here [student performSelector : NSSelectorFromString(@setAge:) withObject : [NSNumber numberWithInt : 19]]; ^ 1 warning generated. bogon:6.6 octopus$ ./a.out 2015-10-06 12:00:41.669 a.out[747:507] age is : 18 2015-10-06 12:00:41.671 a.out[747:507] age is : 19 2015-10-06 12:00:41.671 a.out[747:507] age is : 20 2015-10-06 12:00:41.672 a.out[747:507] age is : 21
以上便是 Objective-C 進階物件導向特性的完整梳理。掌握這些機制,能讓你在面對大型專案與系統框架時更加游刃有餘。