为有牺牲多壮志,敢教日月换新天。

[Objective-C语言教程]动态绑定(32)

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

动态绑定确定在运行时而不是在编译时调用的方法。 动态绑定也称为后期绑定。 在Objective-C中,所有方法都在运行时动态解析。执行的确切代码由方法名称(选择器)和接收对象确定。

动态绑定可实现多态性。例如,考虑一组对象,包括RectangleSquare。 每个对象都有自己的printArea方法实现。

在下面的代码片段中,表达式[anObject printArea]执行的实际代码是在运行时确定的。 运行时系统使用方法运行的选择器来识别anObject的任何类中的适当方法。

下面来看一下解释动态绑定的简单代码 -

 1 #import <Foundation/Foundation.h>
 2 
 3 @interface Square:NSObject {
 4    float area;
 5 }
 6 
 7 - (void)calculateAreaOfSide:(CGFloat)side;
 8 - (void)printArea;
 9 @end
10 
11 @implementation Square
12 - (void)calculateAreaOfSide:(CGFloat)side {
13    area = side * side;
14 }
15 
16 - (void)printArea {
17    NSLog(@"The area of square is %f",area);
18 }
19 
20 @end
21 
22 @interface Rectangle:NSObject {
23    float area;
24 }
25 
26 - (void)calculateAreaOfLength:(CGFloat)length andBreadth:(CGFloat)breadth;
27 - (void)printArea;
28 @end
29 
30 @implementation  Rectangle
31 
32 - (void)calculateAreaOfLength:(CGFloat)length andBreadth:(CGFloat)breadth {
33    area = length * breadth;
34 }
35 
36 - (void)printArea {
37    NSLog(@"The area of Rectangle is %f",area);
38 }
39 
40 @end
41 
42 int main() {
43    Square *square = [[Square alloc]init];
44    [square calculateAreaOfSide:8.0];
45 
46    Rectangle *rectangle = [[Rectangle alloc]init];
47    [rectangle calculateAreaOfLength:10.0 andBreadth:20.0];
48 
49    NSArray *shapes = [[NSArray alloc]initWithObjects: square, rectangle,nil];
50    id object1 = [shapes objectAtIndex:0];
51    [object1 printArea];
52 
53    id object2 = [shapes objectAtIndex:1];
54    [object2 printArea];
55 
56    return 0;
57 }

执行上面示例代码,得到以下结果 -

1 2018-11-16 03:16:53.399 main[53860] The area of square is 64.000000
2 2018-11-16 03:16:53.401 main[53860] The area of Rectangle is 200.000000

正如在上面的示例中所看到的,printArea方法是在运行时动态选择调用的。 它是动态绑定的一个示例,在处理类似对象时在很多情况下非常有用。

posted @ 2019-03-21 15:39  为敢技术  阅读(177)  评论(0编辑  收藏  举报