Objective-Cの動的バインディング
動的バインディングは、コンパイル時ではなく実行時に呼び出すメソッドを決定します。動的バインディングは、遅延バインディングとも呼ばれます。Objective-Cでは、すべてのメソッドが実行時に動的に解決されます。実行される正確なコードは、メソッド名(セレクター)と受信オブジェクトの両方によって決定されます。
動的バインディングにより、ポリモーフィズムが可能になります。たとえば、RectangleやSquareなどのオブジェクトのコレクションについて考えてみます。各オブジェクトには、printAreaメソッドの独自の実装があります。
次のコードフラグメントでは、式[anObjectprintArea]によって実行される実際のコードが実行時に決定されます。ランタイムシステムは、実行されるメソッドのセレクターを使用して、オブジェクトのクラスが何であれ、適切なメソッドを識別します。
動的バインディングを説明する簡単なコードを見てみましょう。
#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メソッドは実行時に動的に選択されます。これは動的バインディングの例であり、同様の種類のオブジェクトを処理する多くの状況で非常に役立ちます。