Runtime学习笔记

来源:互联网 发布:潭州学院java vip视频 编辑:程序博客网 时间:2024/06/05 20:26

1.什么是运行时(Runtime)?1> Runtime System* 所有的iOS程序的幕后支撑着都是运行时系统* iOS程序的方法调用都是要靠运行时系统来支持的2> Runtime Library* 一套苹果提供的纯C语言的库(API)* 运行时库的作用a)能为一个类动态添加成员变量、动态添加方法、动态修改方法的实现b)能动态交换2个方法的实现(可以给系统自带的方法替换实现)*本质上,开发者的编写的OC代码最终都是转成了运行时代码
- (void)test{    NSLog(@"123");}// NSString 抽象类 不允许继承[UIImage imageName:@"home.png"];- (void)test{    NSLog(@"run");}
2.OC代码对应的C++代码* 命令行a)进入main.m对应的上层文件夹   >clang -rewrite-objc main.m>ls -l  (查看是否有main.cpp文件)>open main.cppOC代码与cpp代码如下:
#import <Foundation/Foundation.h>#import <objc/runtime.h>#import <objc/message.h>int main(int argc, const char * argv[]) {    @autoreleasepool {        // insert code here...        NSObject * obj = [[NSObject alloc] init];        [obj description];       id other = objc_msgSend(objc_getClass("NSObject"), sel_registerName("alloc"))        NSObject * obj = objc_msgSend(other, sel_registerName("init"));        objc_msgSend(obj, sel_registerName("description"));    }    return 0;}
3.Runtime在实际中的应用应用场景:iOS6向iOS7过渡时风格有较大改变,一些公司需要在不同的系统上呈现不同的应用风格,因此,开发人员需要在6的基础上添加7对应的图片,图片可能是成百上千张的,因为对每一张图片进行系统判断再处理是相当麻烦的,所以我们可以使用运行时来解决这个问题。
#import <UIKit/UIKit.h>@interface ViewController : UIViewController@property (nonatomic, strong)UIImageView * imageView;@end
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    [self setupSubviews];    self.imageView.image = [UIImage imageNamed:@"close"]; }- (void)setupSubviews{    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];    [self.view addSubview:_imageView];}@end
#import "UIImage+Extension.h"#import <objc/runtime.h>@implementation UIImage (Extension)/** *   将类装载进内存就会调用1次 */+ (void)load{    Method originalMethod = class_getClassMethod([UIImage class], @selector(imageNamed:));    Method diyMethod = class_getClassMethod([UIImage class], @selector(yk_imageNamed:));    method_exchangeImplementations(originalMethod, diyMethod);}+ (UIImage *)yk_imageNamed:(NSString *)name{    CGFloat systemVersion = [[UIDevice currentDevice].systemVersion floatValue];    if(systemVersion >= 7.0){        name = [name stringByAppendingString:@"_os7"];    }    return [UIImage yk_imageNamed:name];}@end
0 0