首页 > 学院 > 开发设计 > 正文

runtime 动态添加方法实现方法懒加载

2019-11-06 10:03:37
字体:
来源:转载
供稿:网友

#import <Foundation/Foundation.h>

@interface Dog : NSObject

@end _______________________________________________

#import "Dog.h" #import <UIKit/UIKit.h> #import <objc/message.h>

@implementation Dog

//当类方法或对象方法没有实现就会调用这两个方法中的一个 //处理类方法 //+(BOOL)resolveClassMethod:(SEL)sel //处理对象方法 //+(BOOL)resolveInstanceMethod:(SEL)sel

+(BOOL)resolveInstanceMethod:(SEL)sel {

NSLog(@"%@方法没有实现",NSStringFromSelector(sel));if (sel == @selector(wangwangwang:)) {//动态添加方法/* cls: 类类型 name: 方法编号 imp: 方法实现,函数指针 types: 函数类型 C字符串(Code)void === "v" */class_addMethod([Dog class], sel, (IMP)wangwangwang, "v@:@");} else if( sel ==@selector(wangwangwang1) ){ //参数意义具体参考官方文档 class_addMethod([Dog class], sel, (IMP)wangwangwang1, "v@:");}return [super resolveClassMethod:sel];

}

void wangwangwang(id self, SEL _cmd,id obj) {

NSLog(@"带参数%@",obj);

}

void wangwangwang1(id self, SEL _cmd) {

NSLog(@"不带参数");

}

@end _______________________________________________ 调用 #import "HJViewController.h" #import "Dog.h" @interface HJViewController ()

@end

@implementation HJViewController

- (void)viewDidLoad { [super viewDidLoad];

//方法懒加载 动态添加方法Dog *dog = [[Dog alloc]init];[dog performSelector:@selector(wangwangwang1)];[dog performSelector:@selector(wangwangwang:) withObject:@"汪汪汪"];

}

@end


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表