Swizzle运行时

#import <Foundation/Foundation.h>


//获取一个类的所有属性名字:类型的名字,具有@property, 父类的获取不了!

NSDictionary *GetPropertyListOfObject(NSObject *object);

NSDictionary *GetPropertyListOfClass(Class cls);


void Swizzle(Class c, SEL origSEL, SEL newSEL)



//

//  ObjcRuntime.m

//  EMeal_Cook

//

//  Created by Wujg on 15/10/15.

//  Copyright © 2015 Wujg. All rights reserved.

//


#import "ObjcRuntime.h"

#import <objc/runtime.h>


NSDictionary *GetPropertyListOfObject(NSObject *object) {

    return GetPropertyListOfClass([object class]);

}


NSDictionary *GetPropertyListOfClass(Class cls) {

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];

    

    unsigned int outCount, i;

    objc_property_t *properties = class_copyPropertyList(cls, &outCount);

    for(i = 0; i < outCount; i++) {

        objc_property_t property = properties[i];

        const char *propName = property_getName(property);

        const char *propType = property_getAttributes(property);

        if(propType&&propName) {

            NSArray *anAttribute = [[NSString stringWithUTF8String:propType]componentsSeparatedByString:@","];

            NSString *aType = anAttribute[0];

            [dict setObject:aType forKey:[NSString stringWithUTF8String:propName]];

        }

    }

    free(properties);

    

    return dict;

}


//静态就交换静态,实例方法就交换实例方法

void Swizzle(Class c, SEL origSEL, SEL newSEL) {

    Method origMethod = class_getInstanceMethod(c, origSEL);

    Method newMethod = nil;

if (!origMethod) {

origMethod = class_getClassMethod(c, origSEL);

        if (!origMethod) {

            return;

        }

        newMethod = class_getClassMethod(c, newSEL);

        if (!newMethod) {

            return;

        }

    } else {

        newMethod = class_getInstanceMethod(c, newSEL);

        if (!newMethod) {

            return;

        }

    }

    

    //自身已经有了就添加不成功,直接交换即可

    if(class_addMethod(c, origSEL, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {

        class_replaceMethod(c, newSEL, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));

    } else {

        method_exchangeImplementations(origMethod, newMethod);

}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值