views:

211

answers:

3

Is it possible to remove methods added to a class with class_addMethod?

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 :-)

A: 

I don't how to do that. But I guess that a new entry is added for the new method in the list of instance methods for the class in its metaclass. So you want to remove it, you just need to restore the list. You'll have to search in the headers to find the struct where this list lies. I hope this can help.

Pierre Thibault
If you don't know how to do it, don't answer. The answer varies depending on which version of the runtime you are using and, in the modern runtime, you can't muck about in the structures.
bbum
A: 

I guess the question which has yet to be asked is "Why?" Whether it's possible or not, there may be some stability questions involved in pulling methods out from under a class when it's been instantiated and running.

AlBlue
Not an answer to the question, but you definitely make a very good point.
bbum
+1  A: 

In short, you can't.

You could in the Objective-C 1.0 ABI/API via:

OBJC_EXPORT void class_removeMethods(Class, struct objc_method_list *) OBJC2_UNAVAILABLE;

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.

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.

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%5FClass/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.

bbum
The answer to "why" is that I am interested in writing some code that will show what happens when KVC is used. By adding and removing methods at runtime I could allow the user to explore the effect of having various combinations of methods present.I have concluded that only way this can be done is by mucking about with the internals; and Objective-C 2.0 puts a stop to that by all means except hackery.
Steve Weller