通过ObjC类别重写方法并调用默认实现? [英] Override a method via ObjC Category and call the default implementation?

查看:115
本文介绍了通过ObjC类别重写方法并调用默认实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用类别时,您可以使用自己的类别覆盖实现方法,如下所示:

When using categories, you can override implementation methods with your own like so:

// Base Class 
@interface ClassA : NSObject 
- (NSString *) myMethod;
@end
@implementation ClassA
- (NSString*) myMethod { return @"A"; }
@end

//Category
@interface ClassA (CategoryB) 
- (NSString *) myMethod;
@end
@implementation ClassA (CategoryB)
- (NSString*) myMethod { return @"B"; }
@end

包括类别之后,调用方法"myMethod"将得到结果"B".

Calling the method "myMethod" after including the category nets the result "B".

myMethod的Category实现调用原始A类myMethod的最简单方法是什么?据我所知,您必须使用低级调用来获取A类的原始方法钩子并对其进行调用,但是这样做似乎在语法上更简单.

What is the easiest way for the Category implementation of myMethod to call the original Class A myMethod? As near as I can figure out, you'd have to use the low level calls to get the original method hook for Class A and call that, but it seemed like there would be a syntactically easier way to do this.

推荐答案

如果您希望采用一种骇人听闻的方式来实现此目的,而这种方式涉及对Objective-C运行时进行破坏,那么您始终可以使用

If you want a hackish way to do this that involves mucking with the objective-c runtime you can always use method swizzling (insert standard disclaimers here.) It will allow you to store the different methods as arbitrariliy named selectors, then swap them in at runtime as you need them.

这篇关于通过ObjC类别重写方法并调用默认实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆