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 方法是在執行時動態選擇的。它是一個動態繫結的示例,在處理類似物件時在許多情況下非常有用。

廣告