您的位置:首页 > 移动开发 > Objective-C

iOS里面Objective-C(OC)方法的懒加载

2017-07-27 13:18 543 查看
iOS里面Objective-C(OC)方法的懒加载 俗称在运行过程中动态的添加方法。

1、先创建Person类 把#import “Pseron.h” 引入 ViewController

#import "ViewController.h"
#import "Pseron.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

Pseron * p = [[Pseron alloc]init];
//懒加载  用到的时候在加载方法!!
[p performSelector:@selector(eat)];
[p performSelector:@selector(eat:) withObject:@"板烧鸡腿堡"];

}


2、这样编译时 是报错的,因为这个方法是没有实现的,现在我们要去动态的添加方法:来到Pseron.h

#import "Pseron.h"
#import <objc/message.h>

@implementation Pseron

//C语言的
//所有的C语言的函数里面!都有这两个隐式参数!只要调用,哥么系统都会传递进来!
//不带参数的
void eat(id self, SEL _cmd){
NSLog(@"调用了%@对象的%@方法",self,NSStringFromSelector(_cmd));
}
//带参数的
void eat1(id self, SEL _cmd,id obj){
NSLog(@"哥么今晚吃五个%@",obj);
}

//当这个类被调用了没有实现的方法!就会来到这里
+(BOOL)resolveInstanceMethod:(SEL)sel{
// NSLog(@"你没有实现这个方法%@",NSStringFromSelector(sel));
if (sel == @selector(eat)) {
//这里报黄色警告的话,没问题的,因为系统编译的时候不知道用了runtime已经添加了这个方法
/*
1.cls: 类类型
2.name: 方法编号
3.imp: 方法实现,函数指针!
4.types:函数类型 C字符串(代码) void === "v"
5.cmd+shift+0去看文档
*/
class_addMethod([Pseron class],sel, (IMP)eat, "v@:");

}else if(sel == @selector(eat:)){

class_addMethod([Pseron class], sel, (IMP)eat1, "v@:@");
}

return [super resolveInstanceMethod:sel];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  objective-c ios 界面 class