動態(tài)綁定在運行時要調(diào)用的方法,而不是在編譯時確定。也被稱為動態(tài)綁定后期綁定。
Objective-C中,所有的方法都解決了在運行時動態(tài)。是由方法名稱(選擇器)和接收消息的對象所執(zhí)行的確切的代碼。
動態(tài)綁定能夠多態(tài)性。例如,考慮的對象,包括 Rectangle 和Square集合。每個對象都有自己實現(xiàn)printArea 方法。
在下面的代碼片段,表達應執(zhí)行的實際代碼 [anObject printArea] 在運行時確定。運行系統(tǒng)使用選擇運行的方法,以確定適當?shù)姆椒ㄔ谌魏晤悓ο蟆?/p>
讓我們來看看一個簡單的代碼,這可以解釋動態(tài)綁定。
#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; }
現(xiàn)在,當我們編譯并運行程序,我們會得到以下的結果。
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 方法是在運行時動態(tài)選擇。這是一個動態(tài)綁定的例子,在同類對象打交道時情況下是非常有用。