runtime与动态添加方法

Posted 壮志凌云的博客园

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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, "[email protected]:");
        return YES;
    } else if (sel == NSSelectorFromString(@"eat:")) {
        class_addMethod(self, sel, (IMP)eat, "[email protected]:@");
        return YES;
    }
    
    return [super resolveInstanceMethod:sel];
    
}

@end

 

以上是关于runtime与动态添加方法的主要内容,如果未能解决你的问题,请参考以下文章

Runtime(运行时)003-动态添加方法

使用runtime给类动态添加方法并调用 - class_addMethod

iOS-Runtime之class_addMethod给类动态添加方法

Objective-C Runtime 文档翻译—与Runtime的相互作用

Runtime 运行时:类与对象

RunTime之类与对象