runtime

iOS之runtime总结

2017-04-28  本文已影响48人  charlotte2018

一、runtime简介

RunTime简称运行时。OC就是运行时机制,也就是在运行时候的一些机制,其中最主要的是消息机制。
对于C语言,函数的调用在编译的时候会决定调用哪个函数。
对于OC的函数,属于动态调用过程,在编译的时候并不能决定真正调用哪个函数,只有在真正运行的时候才会根据函数的名称找到对应的函数来调用。
事实证明:
在编译阶段,OC可以调用任何函数,即使这个函数并未实现,只要声明过就不会报错。
在编译阶段,C语言调用未实现的函数就会报错

二、runtime的一些使用方法

1.发送消息

方法调用的本质,就是让对象发送消息。
objc_msgSend,只有对象才能发送消息,因此以objc开头.
使用消息机制前提,必须导入#import <objc/message.h>
消息机制简单使用

   Dog *dog = [Dog new];
    //对象调用
    [dog run];
    //类方法
    [Dog play];
    
    //runtime 调用
    //1.在项目配置文件 -> Build Settings -> Enable Strict Checking of objc_msgSend Calls 这个字段设置为 NO, 默认为YES. 在编译你的项目就会发现问题解决了
    
    //2.由于objc_msgSend函数本身是无返回值无参数的函数, 所以要给它强制转换类型
    //((void (*) (id, SEL)) (void *)objc_msgSend)(dog, @selector(run));
    
    //对象方法的调用
    objc_msgSend( dog, @selector(run));
    //类方法调用
    objc_msgSend([Dog class], @selector(play));

2.交换方法

开发使用场景:系统自带的方法功能不够,给系统自带的方法扩展一些功能,并且保持原有的功能。
方式一:继承系统的类,重写方法.
方式二:使用runtime,交换方法.


#import "ViewController.h"
#import "UIImage+extension.h"
#import <objc/message.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
  
    // 需求:给imageNamed方法提供功能,每次加载图片就判断下图片是否加载成功。
    // 步骤一:先搞个分类,定义一个能加载图片并且能打印的方法+ (instancetype)imageWithName:(NSString *)name;
    // 步骤二:交换imageNamed和ybimageWithName的实现,就可以间接调用ybimageWithName的实现。
    UIImage *image = [UIImage imageNamed:@"qqq"];
    
}
@end

#import "UIImage+extension.h"
#import <objc/message.h>

@implementation UIImage (extension)

// 加载分类到内存的时候调用
+ (void)load
{
    // 交换方法
    
    // 获取imageWithName方法地址
    Method ybimageWithName = class_getClassMethod(self, @selector(ybimageWithName:));
    
    // 获取imageWithName方法地址
    Method imageName = class_getClassMethod(self, @selector(imageNamed:));
    
    // 交换方法地址,相当于交换实现方式
    method_exchangeImplementations(ybimageWithName, imageName);
    
    
    
}

+ (instancetype)ybimageWithName:(NSString *)name
{
    //// 这里调用ybimageWithName,相当于调用imageName
    UIImage *image = [UIImage ybimageWithName:name];
    
    if (image == nil) {
        NSLog(@"加载空的图片");
    }
    
    return image;
    
}

@end

 

关于埋点的应用 http://www.jianshu.com/p/0497afdad36d
关于解决array传空导致奔溃http://www.jianshu.com/p/080a238c62b9

3.动态添加方法

开发使用场景:如果一个类方法非常多,加载类到内存的时候也比较耗费资源,需要给每个方法生成映射表,可以使用动态给某个类,添加方法解决。
经典面试题:有没有使用performSelector,其实主要想问你有没有动态添加过方法。
简单使用

#import "ViewController.h"
#import "UIImage+extension.h"
#import <objc/message.h>
#import "Dog.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    Dog *d = [Dog new];
    
    [d performSelector:@selector(eat)];
    
    
}


#import "Dog.h"
#import <objc/runtime.h>

@implementation Dog



// void(*)()
// 默认方法都有两个隐式参数,
void eat(id self,SEL sel)
{
    NSLog(@"吃了");
}

// 当一个对象调用未实现的方法,会调用这个方法处理,并且会把对应的方法列表传过来.
// 刚好可以用来判断,未实现的方法是不是我们想要动态添加的方法
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
    
    if (sel == @selector(eat)) {
        // 动态添加eat方法
        
        // 第一个参数:给哪个类添加方法
        // 第二个参数:添加方法的方法编号
        // 第三个参数:添加方法的函数实现(函数地址)
        // 第四个参数:函数的类型,(返回值+参数类型) v:void @:对象->self :表示SEL->_cmd
        class_addMethod(self, @selector(eat), eat, "v@:");
        
    }
    
    return [super resolveInstanceMethod:sel];
}

@end

4.给分类添加属性

1435542766477905.png

原理:给一个类声明属性,其实本质就是给这个类添加关联.

#import "ViewController.h"
#import "Dog+Extension.h"


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    Dog *d = [Dog new];
    
    d.name = @"yellowDog";
    d.age = 12;
    
    NSLog(@"%ld",d.age);
    NSLog(@"%@",d.name);
    
    
}

#import "Dog.h"

@interface Dog (Extension)

@property(nonatomic,strong)NSString *name;

@property(nonatomic,assign)NSInteger age;

@end

#import "Dog+Extension.h"
#import <objc/runtime.h>

static NSString *keyName = @"name";
static NSString *keyAge = @"name";


@implementation Dog (Extension)

- (void)setName:(NSString *)name
{
//    OBJC_ASSOCIATION_ASSIGN = 0, //关联对象的属性是弱引用
//    
//    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, //关联对象的属性是强引用并且关联对象不使用原子性
//    
//    OBJC_ASSOCIATION_COPY_NONATOMIC = 3, //关联对象的属性是copy并且关联对象不使用原子性
//    
//    OBJC_ASSOCIATION_RETAIN = 01401, //关联对象的属性是copy并且关联对象使用原子性
//    
//    OBJC_ASSOCIATION_COPY = 01403 //关联对象的属性是copy并且关联对象使用原子性
    objc_setAssociatedObject(self, &keyName, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)name
{
    return  objc_getAssociatedObject(self, &keyName);
}

- (void)setAge:(NSInteger)age
{
    objc_setAssociatedObject(self, &keyAge, [NSNumber numberWithInteger:age], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSInteger)age
{
    NSNumber *ageNum = objc_getAssociatedObject(self, &keyAge);
    
    return [ageNum integerValue];
}

@end


5.字典转模型


#import "ViewController.h"
#import "Dog.h"
#import "NSObject+Extension.h"


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSDictionary *dic = @{@"name":@"yyyy",@"age":@(12)};
    Dog *d = [Dog modelWithDict:dic];
    
    NSLog(@"%@",d.name);
    NSLog(@"%ld",d.age);
 
    
    
}
@end

@interface Dog : NSObject

@property(nonatomic,strong)NSString *name;

@property(nonatomic,assign)NSInteger age;


@end

#import <Foundation/Foundation.h>

@interface NSObject (Extension)

+ (instancetype)modelWithDict:(NSDictionary *)dict;

@end

#import "NSObject+Extension.h"
#import <objc/runtime.h>

@implementation NSObject (Extension)

+ (instancetype)modelWithDict:(NSDictionary *)dict;
{
    
    
    id obj = [[self alloc]init];
    
    unsigned int count = 0;
    Ivar *ivarList = class_copyIvarList(self, &count);
    
    for (int i = 0 ; i < count; i++) {
        // 获取成员属性
        Ivar ivar = ivarList[i];
        // 获取成员名
        NSString *propertyName = [NSString stringWithUTF8String:ivar_getName(ivar)];
        ;
        // 获取key
        NSString *key = [propertyName substringFromIndex:1];
        
        // 获取字典的value
        id value = dict[key];
        
        if (value) {
            // KVC赋值:不能传空
            [obj setValue:value forKey:key];
            
        }
    }
    
    return obj;
}

@end


归档

http://www.jianshu.com/p/67669eca6ca4

一些方法

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    NSString *_company;
}

@property(nonatomic,copy)NSString *name;

@property(nonatomic,strong)NSArray *array;

- (NSArray *)allPropertiesName;

- (NSDictionary *)allPropertiesNameAndValue;

- (void)allMethods;

- (NSArray *)allVariables;

@end
#import "Person.h"
#import <objc/runtime.h>

@implementation Person


/**
 class_copyPropertyList 获取属性的列表
 property_getName  获取属性的名字
 @return 属性的数组
 */
- (NSArray *)allPropertiesName
{
    unsigned int count;
//  数组指针
    objc_property_t *properties = class_copyPropertyList(self.class, &count);
    NSMutableArray *propertyArray = [NSMutableArray array];
    
    for (int i=0; i<count; i++) {
        
       const char *propertyName = property_getName(properties[i]);
        NSString *name = [NSString stringWithUTF8String:propertyName];
        [propertyArray addObject:name];
    }
    
    //释放内存
    free(properties);
    
    return propertyArray;
}


/**
 获取属性的名字和值

 @return nameAndValueDic
 */
- (NSDictionary *)allPropertiesNameAndValue
{
    unsigned int count;
    //  数组指针 二级指针
    objc_property_t *properties = class_copyPropertyList(self.class, &count);
    NSMutableDictionary *nameAndValueDic = [NSMutableDictionary dictionary];
    
    for (int i=0; i<count; i++) {
        
        const char *propertyName = property_getName(properties[i]);
        NSString *name = [NSString stringWithUTF8String:propertyName];
        id value = [self valueForKey:name];
        if (value && name) {
            [nameAndValueDic setObject:value forKey:name];
        }
    }
    
    //释放内存
    free(properties);
    
    return nameAndValueDic;
}


/**
 获取对象的所有方法名及参数个数
 */
- (void)allMethods
{
    unsigned int count = 0;
    Method *methods = class_copyMethodList(self.class, &count);
    for (int i=0; i<count; i++) {
        
        Method method = methods[i];
        SEL methodSEL = method_getName(method);
        const char* name = sel_getName(methodSEL);
        NSString *methodName = [NSString stringWithUTF8String:name];
        int argumentCount = method_getNumberOfArguments(method);
        NSLog(@"方法名: %@ 参数个数:%d",methodName,argumentCount);
    }
    
    free(methods);
}

/**
  获取对象的成员变量
 */
- (NSArray *)allVariables
{
    NSMutableArray *ivarArray = [NSMutableArray array];
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList(self.class, &count);
    for (int i=0; i<count; i++) {
        Ivar varialbe = ivars[i];
        const char *name = ivar_getName(varialbe);
        NSString *varName = [NSString stringWithUTF8String:name];
        [ivarArray addObject:varName];
    }
    
    free(ivars);
    
    return ivarArray;
}

@end

上一篇下一篇

猜你喜欢

热点阅读