美文网首页
运行时的简略介绍

运行时的简略介绍

作者: 未来的路就在那 | 来源:发表于2017-05-05 14:00 被阅读18次
  1. 获得类(包括范畴类)或者协议类中的属性和变量列表
objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)
objc_property_t *protocol_copyPropertyList(Protocol *proto, unsigned int *outCount)
Ivar * iVars=class_copyIvarList([self class], &count);
####class_copyPropertyList返回的仅仅是对象类的属性(@property申明的属性),而class_copyIvarList返回类的所有属性和变量(包括在@interface大括号中声明的变量),

事例

#####获取属性列表
    NSMutableArray * pNames = [[NSMutableArray alloc]init];
    unsigned int count ;
    objc_property_t * propertys=class_copyPropertyList([self class], &count);
    for (int i = 0; i<count; i++) {
         const char * pty = property_getName(propertys[i]);
        [pNames addObject:[NSString stringWithUTF8String:pty]];
    }
    free(propertys);//必须释放
    return  [pNames copy];
######获取属性的特性
   NSMutableArray * pNamesAttr = [[NSMutableArray alloc]init];
    unsigned int count ;
    objc_property_t * propertys=class_copyPropertyList([self class], &count);
    for (int i = 0; i<count; i++) {
        const char * pty = property_getAttributes(propertys[i]);
        [pNamesAttr addObject:[NSString stringWithUTF8String:pty]];
    }
    free(propertys);//必须释放
    return  [pNamesAttr copy];
(weak,readonly等等)
######类的所有属性和变量
   NSMutableArray * ivarNames = [[NSMutableArray alloc]init];
    unsigned int count ;
    Ivar * iVars=class_copyIvarList([self class], &count);
    for (int i = 0; i<count; i++) {
        const char * var  = ivar_getName(iVars[i]);
        //选择性赋值.
        if (strcmp(var , "privateIvar")==0) {
            object_setIvar(self, iVars[i], @"runTime");//赋值
            object_getIvar(self, iVars[i]);//这里是读取值
        }
        [ivarNames addObject:[NSString stringWithUTF8String:var]];
    }
    free(iVars);//必须释放
    return  [ivarNames copy];
######property_getName   是拿到属性的名字
######property_getAttributes是拿到属性的是属性的特性
  1. 查看所有的方法的返回值和参数类型
#class_copyMethodList-获取类的所有方法列表 
    //MAXLenth 其实没有必要为100,只是系统给的方法必须要传递一个长度,自己只能根据返回值估计一个。防止复制的长度不够,实际上10也许就够了
    unsigned int methodCount;
    //Method方法默认的参数有两个的
#pragma mark -- OC里面的方法在运行时都是转换为了objc_send函数,这个方法第一个参数是调用者,第二个是方法名。默认的两个参数就是调用者和方法名
    Method  *methods = class_copyMethodList([self class], &methodCount);
    for (int i=0; i<methodCount; i++) {
        SEL methodSel = method_getName(methods[i]);//先转换为SEL类型,消息选择器
        NSLog(@"方法的名字 = %s",sel_getName(methodSel));
        unsigned argumentCnt = method_getNumberOfArguments(methods[i]);
        NSLog(@"方法的参数个数 number = %d ",argumentCnt);
        for (int j = 0 ; j< argumentCnt;j++) {
            char argumentsType[MAXLength];
            method_getArgumentType(methods[j], j, argumentsType, MAXLength);
            NSLog(@"第%d个参数是%s",j,argumentsType);
        }
        char returnType[MAXLength];
        method_getReturnType(methods[i], returnType, MAXLength);
        NSLog(@"方法的返回类型%s",returnType);
        //方法的实现
        /**
         A pointer to the start of a method implementation.
         Declaration
         id (*IMP)(id, SEL, ...)
         指向方法的函数指针
         */
//#pragma waring --- IMP暂时不会用,后面的class_addMethod方法用到了动态添加方法
        IMP imp = method_getImplementation(methods[i]);
    }
    free(methods);
  1. 运行时调用方法
一. 已经声明并实现了方法
    //无参数
   ((void(*)(id,SEL)) objc_msgSend)(swift,@selector(executeMethodByRunTime_00));
    //有参数
    ((void(*)(id,SEL,NSString*)) objc_msgSend)(swift,@selector(executeMethodByRunTime_01:),@"runtime param");
    //有参数有返回值
    NSString * returnS = ((NSString *(*)(id,SEL,NSString*)) objc_msgSend)(swift,@selector(executeMethodByRunTime_02:),@"hello");
    NSLog(@"%@",returnS);
二.或者没声明,或者没实现,或者没声明和实现。
1.只声明未定义 ,动态添加方法来执行(本类中添加)
-(NSString *)onlyDeclareMethod:(NSString *)first andWithSec:(NSString*)second;//声明
   NSString * name = [swift onlyDeclareMethod:@"xiaobai" andWithSec:@"yige"]; //调用
/**
 This method is called before the Objective-C forwarding mechanism is invoked. If respondsToSelector: or instancesRespondToSelector: is invoked, the dynamic method resolver is given the opportunity to provide an IMP for the given selector first.
 这个方法会在OC的转发机制前被调用,respondsToSelector,instancesRespondToSelector方法被调用了,这个方法会首先给一个机会提供一个方法的实现
 */
 (BOOL)resolveInstanceMethod:(SEL)sel
{
   // you can use resolveInstanceMethod: to dynamically add it to a class as a method (called resolveThisMethodDynamically) like this:
        //根据苹果的文档,自己解决在,函数
    if (sel == @selector(onlyDeclareMethod:andWithSec:))//可以在为没有实现的方法添加动态添加一个方法
    {
            //最后一个参数是函数的参数和返回值类型,可以根据文档查阅具体的,从左到右依次是函数返回值和各个参数
            //第一个@表示返回值是对象(NSString*)是对象的一种,第二个@表示的是第一个参数id类型,":"表示参数SEL类型,后面两个表示
            //first和second
            class_addMethod([self class], sel, (IMP)implementOnlyDeclare, "@@:@@");
            return YES;
    }
    return [super resolveInstanceMethod:sel];
    //最后一位是函数的编码格式,需要查看手册
    //class_addMethod(self, sel, (IMP)implementMethod, "v");
}
//--实现动态添加的方法
//--- 自己动态为没有实现的方法添加一个方法,class_addMethod方法添加的方法至少包含两个参数,id,_cmd,自己猜测是因为这里添加的是方法是
//OC的方法,OC的方法在运行时中的C语言方法执行时用的objc_msgSend函数调用格式有关
NSString *implementOnlyDeclare(id class ,SEL sel,NSString * first,NSString * second)
{
    return [NSString stringWithFormat:@"在resolveInstanceMethod中通过addMethod方法实现方法:%@+%@",first,second];
}
2.只声明未定义 ,动态添加方法来执行(其它类中添加)
// 2.resolveInstanceMethod:(SEL)sel 未找到正确的方法会执行,会走到这个方法
//用于指定哪个对象响应这个selector。不能指定为self。若返回nil,表示没有响应者,则会进入第三步。若返回某个对象,则会调用该对象的方法
 (id)forwardingTargetForSelector:(SEL)aSelector
{
    if (aSelector == @selector(onlyDeclareMethod2:andWithSec:)) {
        
        return [[Pen alloc]init];//由Pen类代替自己去处理
    }
    return nil;
}
  1. 运行时解决类扩展属性测试,相当于为oc类动态的添加属性。
######动态添加属性
//调用
    Pen * testCate = [[Pen alloc]init];
    testCate.catePen = @"category_nocrash";
//在Pen类的分类中实现
//动态的添加属性
 (void)setCatePen:(NSString *)catePen
{
    //这个函数:Sets an associated value for a given object using a given key and association policy.
    //把一个值和一个对象用一个key和关联规则关联起来。第一个参数关联对象,第二个是key,第三个是关联的值,第四个关联规则,类似于
    //nonatomic,assin,copy,retain
    objc_setAssociatedObject(self, catePen_Key, catePen, OBJC_ASSOCIATION_RETAIN);
}
(NSString*)catePen
{
    NSString * cateName= objc_getAssociatedObject(self, catePen_Key);//通过一个键值和对象取得对应的值。
    return cateName;
}
#######动态交换执行方法
(void)load
{
    [super load];
    Method originMethod = class_getInstanceMethod([self class], @selector(executeDefalut2));
    Method newMethod = class_getInstanceMethod([self class], @selector(swizzingMethod));
    method_exchangeImplementations(originMethod, newMethod);
}
(NSString *)swizzingMethod
{
    return @"swizzing 方法替换了executeDefalut2";
}

demo下载地址
原文学习地址-http://www.jianshu.com/p/eec3dbd5efcf

相关文章

网友评论

      本文标题:运行时的简略介绍

      本文链接:https://www.haomeiwen.com/subject/iupjtxtx.html