首页 > 代码库 > runtime与动态添加方法

runtime与动态添加方法

代码-ViewController.m: 

#import "ViewController.h"
#import "Dog.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    Dog *dog = [[Dog alloc] init];
    [dog performSelector:NSSelectorFromString(@"run")];
    [dog performSelector:NSSelectorFromString(@"eat:") withObject:@"bones"];
}

@end

 代码-Dog.h:

#import <Foundation/Foundation.h>

@interface Dog : NSObject

@end

代码-Dog.m:

#import "Dog.h"
#import <objc/runtime.h>

void run(id self, SEL _cmd) {
    NSLog(@"%s", __FUNCTION__);
}

void eat(id self, SEL _cmd, NSString *foodName) {
    NSLog(@"%s %@", __FUNCTION__, foodName);
}

@implementation Dog

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    
    if (sel == NSSelectorFromString(@"run")) {
        class_addMethod(self, sel, (IMP)run, "v@:");
        return YES;
    } else if (sel == NSSelectorFromString(@"eat:")) {
        class_addMethod(self, sel, (IMP)eat, "v@:@");
        return YES;
    }
    
    return [super resolveInstanceMethod:sel];
    
}

@end

 

runtime与动态添加方法