動態綁定確定在運行時而不是在編譯時調用的方法。 動態綁定也稱為後期綁定。 在Objective-C中,所有方法都在運行時動態解析。執行的確切代碼由方法名稱(選擇器)和接收對象確定。
動態綁定可實現多態性。例如,考慮一組對象,包括Rectangle
和Square
。 每個對象都有自己的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:8.0];
Rectangle *rectangle = [[Rectangle alloc]init];
[rectangle calculateAreaOfLength:10.0 andBreadth:20.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;
}
執行上面示例代碼,得到以下結果 -
2018-11-16 03:16:53.399 main[53860] The area of square is 64.000000
2018-11-16 03:16:53.401 main[53860] The area of Rectangle is 200.000000
正如在上面的示例中所看到的,printArea
方法是在運行時動態選擇調用的。 它是動態綁定的一個示例,在處理類似對象時在很多情況下非常有用。
上一篇:
Objective-C協議
下一篇:
Objective-C複合對象