The meta class is useful when wishing to view, add or modify class methods and class-level information.
For example,
IMP myIMP = imp_implementationWithBlock(^(id _self, NSString *string) {
NSLog(@"Hello %@", string);
});
Class cls = objc_getMetaClass("NSString");
class_addMethod(cls, @selector(test:), myIMP, "v@:@");
[NSString test:@"lala"];
To get instance methods, you use class_copyMethodList()
on the class returned by class
method on an object or NSClassFromString()
. You will get an array of all the instance methods defined by the class (but not of its superclass!). You can then use the various method_*()
methods to retrieve information and possibly even modify these methods (like implementation swizzling).
You can call class_copyMethodList()
on the meta class to get all the class methods defined.
To address your "Leo" questions,
1.
Please read the Objective C Runtime Reference. You can find a section of method_
functions dealing with Method
structs.
2. See tutorial on implementation swizzling.
3. Using Objective C, everything is available to the runtime. It goes without saying, that with great power comes great responsibility. The Objective C runtime is very powerful. These swizzles are very dangerous and usually not recommended.