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 方法是在运行时动态选择的。 它是动态绑定的示例,在处理类似对象的许多情况下非常有用。

