
- Objective-C 基礎
- Objective-C - 首頁
- Objective-C - 概述
- Objective-C - 環境設定
- Objective-C - 程式結構
- Objective-C - 基本語法
- Objective-C - 資料型別
- Objective-C - 變數
- Objective-C - 常量
- Objective-C - 運算子
- Objective-C - 迴圈
- Objective-C - 決策
- Objective-C - 函式
- Objective-C - 塊
- Objective-C - 數字
- Objective-C - 陣列
- Objective-C - 指標
- Objective-C - 字串
- Objective-C - 結構體
- Objective-C - 預處理器
- Objective-C - Typedef
- Objective-C - 型別轉換
- Objective-C - 日誌處理
- Objective-C - 錯誤處理
- 命令列引數
- 高階 Objective-C
- Objective-C - 類與物件
- Objective-C - 繼承
- Objective-C - 多型
- Objective-C - 資料封裝
- Objective-C - 分類
- Objective-C - 偽裝
- Objective-C - 擴充套件
- Objective-C - 協議
- Objective-C - 動態繫結
- Objective-C - 複合物件
- Obj-C - Foundation 框架
- Objective-C - 快速列舉
- Obj-C - 記憶體管理
- Objective-C 有用資源
- Objective-C - 快速指南
- Objective-C - 有用資源
- Objective-C - 討論
Objective-C 動態繫結
動態繫結是在執行時而不是在編譯時確定要呼叫的方法。動態繫結也稱為後期繫結。在 Objective-C 中,所有方法都在執行時動態解析。執行的確切程式碼由方法名稱(選擇器)和接收物件共同決定。
動態繫結支援多型。例如,考慮一個包含矩形和正方形的物件集合。每個物件都有自己實現的 printArea 方法。
在以下程式碼片段中,表示式 [anObject printArea] 應執行的實際程式碼是在執行時確定的。執行時系統使用執行方法的選擇器來識別 anObject 所屬類的適當方法。
讓我們看一個簡單的程式碼,它將解釋動態繫結。
#import <Foundation/Foundation.h> @interface Square:NSObject { float area; } - (void)calculateAreaOfSide:(CGFloat)side; - (void)printArea; @end @implementation Square - (void)calculateAreaOfSide:(CGFloat)side { area = side * side; } - (void)printArea { NSLog(@"The area of square is %f",area); } @end @interface Rectangle:NSObject { float area; } - (void)calculateAreaOfLength:(CGFloat)length andBreadth:(CGFloat)breadth; - (void)printArea; @end @implementation Rectangle - (void)calculateAreaOfLength:(CGFloat)length andBreadth:(CGFloat)breadth { area = length * breadth; } - (void)printArea { NSLog(@"The area of Rectangle is %f",area); } @end int main() { Square *square = [[Square alloc]init]; [square calculateAreaOfSide:10.0]; Rectangle *rectangle = [[Rectangle alloc]init]; [rectangle calculateAreaOfLength:10.0 andBreadth:5.0]; NSArray *shapes = [[NSArray alloc]initWithObjects: square, rectangle,nil]; id object1 = [shapes objectAtIndex:0]; [object1 printArea]; id object2 = [shapes objectAtIndex:1]; [object2 printArea]; return 0; }
現在,當我們編譯並執行程式時,我們將獲得以下結果。
2013-09-28 07:42:29.821 demo[4916] The area of square is 100.000000 2013-09-28 07:42:29.821 demo[4916] The area of Rectangle is 50.000000
如您在上面的示例中看到的,printArea 方法是在執行時動態選擇的。它是一個動態繫結的示例,在處理類似物件時在許多情況下非常有用。
廣告