簡體   English   中英

Objective-C中的多態性-iOS

[英]Polymorphism in Objective-C - iOS

我已經在C ++中使用多態了很長時間了,我更喜歡使用它。 Objective-C是否具有此功能? 也許與代表有關?

我從事iOS開發已有一段時間,並且一直在使用諸如MessageUI和iAd之類的框架。

因此,當我導入這些類型的框架,然后使用這種方法時,例如:

- (void)mailComposeController:(MFMailComposeViewController*)controller  
      didFinishWithResult:(MFMailComposeResult)result 
                    error:(NSError*)error;

這是否意味着我實質上在Objective-C中使用了多態?

根據定義,“多態”一詞意味着多種形式。

一般而言,多態是一個非常廣泛的主題,基本上它會調用許多方法,例如方法重載,運算符重載,繼承,可重用性。

而且我不認為我實現了多態,而是使用了特定的術語,例如繼承,運算符重載,方法重載等。

Objective-C多態性意味着對成員函數的調用將導致執行不同的函數,具體取決於調用該函數的對象的類型。

例如 -

我有一個基類Shape ,定義為-

#import <Foundation/Foundation.h>

@interface Shape : NSObject {

    CGFloat area;
}

- (void)printArea;
- (void)calculateArea;
@end

@implementation Shape

- (void)printArea {
    NSLog(@"The area is %f", area);
}

- (void)calculateArea {
}

@end

我從Shape派生了兩個基類SquareRectangle作為-

@interface Square : Shape { 

    CGFloat length;
}

- (id)initWithSide:(CGFloat)side;

- (void)calculateArea;

@end

@implementation Square

- (id)initWithSide:(CGFloat)side {
    length = side;
    return self;
}

- (void)calculateArea {
    area = length * length;
}

- (void)printArea {
    NSLog(@"The area of square is %f", area);
}

@end

@interface Rectangle : Shape {

    CGFloat length;
    CGFloat breadth;
}

- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth;

@end

@implementation Rectangle

- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth {
    length = rLength;
    breadth = rBreadth;
    return self;
}

- (void)calculateArea {
    area = length * breadth;
}

@end

現在,任何對象上的調用方法都將按以下方式調用相應類的方法:

int main(int argc, const char * argv[]) {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    Shape *square = [[Square alloc]initWithSide:10.0];
    [square calculateArea];
    [square printArea];
    Shape *rect = [[Rectangle alloc]
    initWithLength:10.0 andBreadth:5.0];
    [rect calculateArea];
    [rect printArea];        
    [pool drain];
    return 0;
}

就像你問的那樣

- (void)mailComposeController:(MFMailComposeViewController*)controller  
      didFinishWithResult:(MFMailComposeResult)result 
      error:(NSError*)error;

上面的方法是MFMailComposeViewController類的委托方法,是的,因為它是由委托實現者實現的,因此它可以根據法律准則中的要求進行自定義實現,因此它也是一種多態形式(因為委托方法可以以多種方式實施)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM