发布于 2015-07-05 11:53:53 | 224 次阅读 | 评论: 0 | 来源: 网络整理

动态绑定在运行时要调用的方法,而不是在编译时确定。也被称为动态绑定后期绑定。

Objective-C中,所有的方法都解决了在运行时动态。是由方法名称(选择器)和接收消息的对象所执行的确切的代码。

动态绑定能够多态性。例如,考虑的对象,包括 Rectangle 和Square集合。每个对象都有自己实现printArea 方法。

在下面的代码片段,表达应执行的实际代码 [anObject printArea]  在运行时确定。运行系统使用选择运行的方法,以确定适当的方法在任何类对象。

让我们来看看一个简单的代码,这可以解释动态绑定。


#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 方法是在运行时动态选择。这是一个动态绑定的例子,在同类对象打交道时情况下是非常有用。

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务