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

2017-04-20  本文已影响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

愿编程让这个世界更美好

上一篇 下一篇

猜你喜欢

热点阅读