动态绑定
动态绑定确定了在运行时而不是在编译时调用的方法。动态绑定也称为后期绑定。在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 Rectg:NSObject {
float area;
}
- (void)calculateAreaOfLength:(CGFloat)length andBreadth:(CGFloat)breadth;
- (void)printArea;
@end
@implementation Rectg
- (void)calculateAreaOfLength:(CGFloat)length andBreadth:(CGFloat)breadth {
area = length * breadth;
}
- (void)printArea {
NSLog(@"The area of Rectg is %f",area);
}
@end
int main() {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Square *square = [[Square alloc]init];
[square calculateAreaOfSide:10.0];
Rectg *rectangle = [[Rectg 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];
[pool drain];
return 0;
}
编译并执行上述代码后,将产生以下结果-
2020-08-21 10:02:40.987 helloWorld[13748:924] The area of square is 100.000000
2020-08-21 10:02:40.994 helloWorld[13748:924] The area of Rectg is 50.000000
如上例所示,在运行时动态选择了printArea方法。它是动态绑定的示例,在处理类似类型的对象的许多情况下非常有用。