首页 > 代码库 > 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与动态添加方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。