繁体   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