objc 关于多态使用的的一点简单总结

Priter

.h
@interface Printer : NSObject
- (void)printer;
@end
.m
@implementation Printer
- (void)printer
{
    NSLog(@"This is Priter!");
}
@end

WHPriter

.h
@interface WhPriter : Printer
@end
.m
@implementation WhPriter
- (void)printer
{
    NSLog(@"This is WHPriter!");
}
@end

ColorPriter

.h
@interface ColorPriter : Printer
@end
.m
@implementation ColorPriter
- (void)printer
{
    NSLog(@"This it ColorPriter!");
}
@end

Person

.h
@class Printer;
@interface Person : NSObject
- (void)usePriter:(__kindof Printer *)priter;
@end
.m
#import "Person.h"
#import "Printer.h"
@implementation Person
- (void)usePriter:(__kindof Printer *)priter
{
    NSLog(@"priter:%@", NSStringFromClass([priter class]));
    [priter printer];
}
@end

main.m

int main(int argc, char * argv[]) {
    Person *person = [[Person alloc] init];
    Printer *whiterPriter = [[WhPriter alloc] init];
    Printer *colorPriter = [[ColorPriter alloc] init];
    [person usePriter:whiterPriter];
}

main.cpp

int main(int argc, char * argv[]) {
      Person *person = ((Person *(*)(id, SEL))(void *)objc_msgSend)((id)((Person *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("Person"),             sel_registerName("alloc")), sel_registerName("init"));
      Printer *whiterPriter = ((WhPriter *(*)(id, SEL))(void *)objc_msgSend)((id)((WhPriter *(*)(id, SEL))(void *                                             )objc_msgSend)((id)objc_getClass("WhPriter"), sel_registerName("alloc")), sel_registerName("init"));
          ((void (*)(id, SEL, Printer *))(void *)objc_msgSend)((id)person, sel_registerName("usePriter:"), (Printer *)whiterPriter);
  }

总结

  • 多态的实现依赖于继承
  • 子类重写父类的方法时不需要在.h文件中再次声明方法
  • 在实现多态时,调用子类的方法只需要引入父类头文件就可以了,不需要引入子类头文件也可以实现子类的方法
  • iOS 7 中引入了 __kindof 特性,所以在使用多态的父类作为参数时可以加入 __kindof 特性,使代码更易读
ps: 如果有不对的地方请指出,相互交流,谢谢!

你可能感兴趣的:(objc 关于多态使用的的一点简单总结)