runtime的使用总结

来源:互联网 发布:剑网三光头捏脸数据 编辑:程序博客网 时间:2024/06/02 19:42

1.动态获得类的所有属性
注:需要导入头文件:#import <objc/runtime.h>

+ (NSArray *)getAllProperties {    NSMutableArray *arrM = [NSMutableArray array];    unsigned int count = 0;    // 获得指定类的所有属性    objc_property_t *properties = class_copyPropertyList([self class], &count);    for (int index = 0; index < count; ++index) {        // 对应的属性        objc_property_t property = properties[index];        const char *name = property_getName(property);        // C语言转OC        NSString *ocName = [[NSString alloc] initWithCString:name encoding:NSUTF8StringEncoding];        [arrM addObject:ocName];    }    return arrM;}

2.动态的遍历一个类的所有成员变量

- (void)viewDidLoad {      [super viewDidLoad];        unsigned int count = 0;    /** Ivar:表示成员变量类型 */      Ivar *ivars = class_copyIvarList([BDPerson class], &count);//获得一个指向该类成员变量的指针    for (int i =0; i < count; i ++) {        //获得Ivar        Ivar ivar = ivars[i];        //根据ivar获得其成员变量的名称--->C语言的字符串        const char *name = ivar_getName(ivar);          NSString *key = [NSString stringWithUTF8String:name];        NSLog(@"%d----%@",i,key);}}

3.为分类添加属性
使用objc_setAssociatedObject方法给分类添加属性,需注意属性的修饰词

const char *XYKey = "XYKey";- (void)setName:(NSString *)name {     //  @param object#> 某个象添加属性     // @param key#>     保存属性值使用key     // @param value#>   属性的值     // @param policy#>  属性修饰词     objc_setAssociatedObject(self, XYKey, name, OBJC_ASSOCIATION_COPY_NONATOMIC);}- (NSString *)name {     return objc_getAssociatedObject(self, XYKey);}//动态的添加一个maskView- (MaskView *)_maskView {    MaskView *maskView = (MaskView *)objc_getAssociatedObject(self, XYMaskViewKey);    if (maskView == nil) {        maskView = [[MaskView alloc] init];        [maskView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.6]];        objc_setAssociatedObject(self, XYMaskViewKey, maskView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);    }    return maskView;}

4.动态交换两个方法的实现
可使用runtime的交互方法,给系统的方法添加功能. 实现 : 添加一个分类 –> 在分类中提供一个需要添加的功能的方法 –> 将这个方法的实现和系统自带的方法的实现交互.

#import <UIKit/UIKit.h>@interface UIImage (XYImage)+ (UIImage *)xy_imageName:(NSString *)imageName;@end

在.m文件中

#import "UIImage+XYImage.h"#import <objc/runtime.h>@implementation UIImage (XYImage)+ (void)load {    Method imageNameMethod = class_getClassMethod(self, @selector(imageNamed:));    Method xy_imageNameMethod = class_getClassMethod(self, @selector(xy_imageName:));    // 交换方法的地址    method_exchangeImplementations(imageNameMethod, xy_imageNameMethod);}+ (UIImage *)xy_imageName:(NSString *)imageName {    UIImage *image = [UIImage xy_imageName:imageName];    if (!image) {        NSLog(@"图片不存在");    }    return image;}

使用:(会打印出图片不存在)

#import "ViewController.h"#import "UIImage+XYImage.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    [UIImage imageNamed:@"abc.png"];}

注:借鉴http://www.jianshu.com/p/364eab29f4f5

0 0