我已经在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
我派生了两个基类,Square
并Rectangle
从Shape
-
@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
class的委托方法,是的,因为它是由委托实现者实现的,所以它可以根据法律准则中的要求进行定制实现,因此它也是一种多态形式(因为委托方法可以是实施方式不只一种)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句