1. method_invoke
Note: way to eliminate compiler warnning
. ENABLE_STRICT_OBJC_MSGSEND = NO;
. int (*action)(id, SEL, int) = (int (*)(id, SEL, int)) objc_msgSend;
Description: Calls the implementation of a specified method.
Declaration: id method_invoke(id receiver,Method m, ...)
Example:
@interface KSModel4CheckMethod : NSObject + (void)classPrint; - (void)instancePrint; @end @implementation KSModel4CheckMethod #define PRINT_CMD NSLog(@"%@", NSStringFromSelector(_cmd)) + (void)classPrint { PRINT_CMD; } - (void)instancePrint { PRINT_CMD; } @end #import <Foundation/Foundation.h> #import <objc/runtime.h> #import <objc/message.h> #import "KSModel4CheckMethod.h" void test_0_getName_NSString(); int main(int argc, const char * argv[]) { @autoreleasepool { test_0_method_invoke(); } return 0; } void test_0_method_invoke() { KSModel4CheckMethod *instance = [[KSModel4CheckMethod alloc] init]; Class clazz = [KSModel4CheckMethod class]; Method clazz_method = class_getClassMethod(clazz, @selector(classPrint)); Method instance_method = class_getInstanceMethod(clazz, @selector(instancePrint)); // Method clazz_method = class_getClassMethod(clazz, @selector(instancePrint)); // Method instance_method = class_getInstanceMethod(clazz, @selector(classPrint)); // method_invoke(clazz, nil); // method_invoke(instance, nil); method_invoke(clazz, clazz_method); method_invoke(clazz, instance_method); method_invoke(instance, clazz_method); method_invoke(instance, instance_method); }
Result:
1. method should be fetched from class
class_getClassMethod(instance, @selector(instancePrint)) or
class_getInstanceMethod(instace, @selector(classPrint)) Return nil
2. 2rd parameter with nil would lead to crash
method_invoke(clazz, nil);
method_invoke(instance, nil);
3. 1rd parameter with instance or class would produce same output
method_invoke(clazz, clazz_method);
method_invoke(clazz, instance_method);
method_invoke(instance, clazz_method);
method_invoke(instance, instance_method);
Deepening:
1.How do methods stored in logic and in physic