iOS之runtime有关

2022-02-18  本文已影响0人  男人宫

一些与runtime有关的交换方法,改变变量的值,动态添加方法,为分类添加属性等的api

    self.p = [Person new];
     self.p.name = @"2008奥运会";
     
    //改变变量的值
    NSLog(@"%@",self.p.name);

    //交换方法
    self.model = [Model new];
    //交换前
    [self.model test1];
    //交换后
    [self changeMethods];
    
    //给分类添加属性
    self.p.colorStr = @"yellor";
    NSLog(@"%@",self.p.colorStr);

//交换方法
- (void)changeMethods
{
    //获取方法
    Method m1 = class_getInstanceMethod(self.model.class, @selector(test1));
    Method m2 = class_getInstanceMethod(self.model.class, @selector(test2));
    method_exchangeImplementations(m1, m2);
    [self.model test1];
}

//给一个类动态添加方法
- (void)addMethod{
    class_addMethod(self.model.class, @selector(modetest), class_getMethodImplementation(self.class, @selector(modetest)), "v@:");
    [self.model performSelector:@selector(modetest)];
}
- (void)modetest
{
    NSLog(@"我为model添加了一个方法");
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//    [self changeName];
    [self addMethod];
}
//改变变量的值
- (void)changeName
{
    Ivar ivar = class_getInstanceVariable(self.p.class, "_name");
    object_setIvar(self.p, ivar, @"2020冬奥会");
    NSLog(@"%@",self.p.name);
}

-------
#import "Person+Color.h"
#import <objc/runtime.h>
@implementation Person (Color)
//@selector(方法名) 
- (void)setColorStr:(NSString *)colorStr
{
    objc_setAssociatedObject(self,@selector(colorStr), colorStr, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)colorStr{
    //_cmd是oc中方法中的隐式参数,如方法里的self一样,
    //_cmd代表当前方法
    return objc_getAssociatedObject(self, _cmd);
}
- (void)eat
{
    NSLog(@"人会吃饭");
}

上一篇下一篇

猜你喜欢

热点阅读