面试篇(六):RunTime 熟悉吗?

RunTime 是做什么的?

RunTime简称运行时。OC就是运行时机制,也就是在运行时候的一些机制,其中最主要的是消息机制

你都在哪些方面用过RunTime,可以举例说明吗?

  • 拦截系统自带的方法调用
1.监控移动端上是否安装了某个App。
#import < objc/runtime.h >

Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");

NSObject *workspace = [LSApplicationWorkspace_class 
performSelector:@selector(defaultWorkspace)];

BOOL installed = [workspace performSelector:@selector(applicationIsInstalled:) 
withObject:@"com.xxxxx.cx"];

NSLog(@"%d",installed);
 
  • 交换方法
1.UIImage 加载图片,图片不存在的时候提示。

#import "UIImage+Category.h"
#import 

@implementation UIImage (Category)

+ (void)load{
    
    // 获取imageWithName方法地址
    Method imageWithName = class_getClassMethod(self, @selector(imageWithName:));
    
    // 获取imageWithName方法地址
    Method imageName = class_getClassMethod(self, @selector(imageNamed:));
    
    // 交换方法地址,相当于交换实现方式
    method_exchangeImplementations(imageWithName, imageName);
    
}

+ (instancetype)imageWithName:(NSString *)name
{
    
    // 这里调用imageWithName,相当于调用imageName
    UIImage *image = [self imageWithName:name];
    
    if (image == nil) {
        NSLog(@"%@ 没有找到图片",name);
    }
    
    return image;
}

面试篇(六):RunTime 熟悉吗?_第1张图片
Log.png

最近比较忙,待更~

你可能感兴趣的:(面试篇(六):RunTime 熟悉吗?)