如何在运行时在Objective-C 2.0中删除实例方法? [英] How do I remove instance methods at runtime in Objective-C 2.0?
问题描述
是否可以使用class_addMethod删除添加到类中的方法?
Is it possible to remove methods added to a class with class_addMethod?
或者如果我想这样做,是否必须继续在运行时使用objc_allocateClassPair创建类,并向它们添加不同的方法集以改变实现的方法?
Or if I want to do this, must I keep creating classes at runtime with objc_allocateClassPair and adding different sets of methods to them to vary the methods implemented?
我会接受包括黑客攻击的答案:-)
I'll accept answers that include hackery :-)
推荐答案
总之,你不能.
您可以通过以下方式在Objective-C 1.0 ABI/API中进行操作:
You could in the Objective-C 1.0 ABI/API via:
OBJC_EXPORT void class_removeMethods(Class, struct objc_method_list *) OBJC2_UNAVAILABLE;
但是在Objective-C 2.0中删除了该函数,因为删除方法几乎永远不是正确的答案.当然,不足以证明支持该功能所产生的开销.
But that function was removed in Objective-C 2.0 because removing methods is pretty much never the right answer. Certainly not often enough to justify the overhead incurred by supporting said feature.
从ObjC2.0 ABI中删除的还有直接访问类/方法结构的能力.它们现在是不透明的,因此将来可以更改它们而不会破坏二进制兼容性.
Also removed from the ObjC2.0 ABI was the ability to directly access the class/method structures. They are now opaque so that they can be changed in the future without breaking binary compatibility.
但是,您可以做的是使用自定义代理,该代理可以更改其响应的方法集.请参阅NSProxy类的文档; http://developer.apple.com/documentation /Cocoa/Reference/Foundation/Classes/NSProxy_Class/Reference/Reference.html
What you could do, though, is use a custom proxy that varies the set of methods that it responds to. See documentation for the NSProxy class; http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSProxy_Class/Reference/Reference.html
当然,这个问题就是您要做什么?"这个问题.这样的动态元编程是非典型的.一旦实例化了一个类,通常就不希望在先前的实例仍可能依赖于所述方法的前提下更改其响应的方法集.
Of course, this question begs the question "What are you trying to do?". Such on the fly meta-programming is atypical. Once a class is instantiated, it isn't normally considered desirable to change the set of methods it responds to under the assumption that previous instantiations may still depend on said methods.
这篇关于如何在运行时在Objective-C 2.0中删除实例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!