美文网首页
Runtime动态获取对象属性的方法

Runtime动态获取对象属性的方法

作者: 小苗晓雪 | 来源:发表于2017-04-20 20:43 被阅读13次
#import "ViewController.h"
#include <objc/runtime.h>

@interface Fruit :NSObject

@property (nonatomic , copy) NSString *name ;
@property (nonatomic , assign) CGFloat price ;
@property (nonatomic , strong) NSString *source ;

@end

@implementation Fruit

@end
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    Fruit *fruit = [[Fruit alloc] init] ;
    fruit.name = @"呵呵~" ;
    fruit.price = 1.5 ;
    unsigned int count = 0 ;
    objc_property_t *properties = class_copyPropertyList(NSClassFromString(@"Fruit"), &count) ;
    for (NSUInteger i = 0; i < count; ++i) {
        //拿到所有的属性:
        objc_property_t property = properties[i] ;
        //拿到所有的属性的名字:
        const char * cName = property_getName(property) ;
        //Cstring转OCString:
        NSString *ocName = [NSString stringWithUTF8String:cName] ;
        NSLog(@"property name = %@ , --> %@" , ocName , [fruit valueForKey:@"price"]) ;
        NSLog(@"%@" , @(count)) ;
    }
    free(properties) ;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

愿编程让这个世界更美好

相关文章

  • Runtime(一):简易字典转模型

    runtime常见引用场景:一、关联对象;二、动态获取对象属性,比如实现一个简易的字典转模型方法。 三、交叉方法(...

  • Runtime动态获取对象属性的方法

    愿编程让这个世界更美好

  • iOS中Runtime常用示例

    Runtime的内容大概有:动态获取类名、动态获取类的成员变量、动态获取类的属性列表、动态获取类的方法列表、动态获...

  • iOS-Runtime

    Runtime的内容大概有:动态获取类名、动态获取类的成员变量、动态获取类的属性列表、动态获取类的方法列表、动态获...

  • runtime基础

    目前我所了解的Runtime内容大约有:动态获取类名、动态获取类的成员变量、动态获取类的属性列表、动态获取类的方法...

  • Runtime

    用法 关联对象 动态获取类的属性 交叉方法

  • runtime的理解(二)

    主要内容 利用 runtime 交换方法 利用 runtime 动态添加方法 利用 runtime 动态添加属性 ...

  • iOS获取手机上安装的APP的名称和版本

    获取到LSApplicationWorkspace的对象可以通过runtime得到该对象的所有属性和方法列表,然后...

  • 【iOS篇】Runtime的应用

    我们可以运用runtime机制做一些事情,动态的获取类的一些属性和方法,动态添加方法和方法交换。 1、获取类名 动...

  • RunTime - 方法交换

    上篇我们讲到了runtime 的动态添加属性和方法,遍历对象的属性列表,今天我们来讲一下runtime里面更好用的...

网友评论

      本文标题:Runtime动态获取对象属性的方法

      本文链接:https://www.haomeiwen.com/subject/qpxrzttx.html