ios runtime遍历属性列表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012198553/article/details/53579957

利用iOS的runtime便利一个类的属性及值:

//ObjectRunTime.h声明文件

#import <Foundation/Foundation.h>

/** 遍历属性列表 */
@interface ObjectRunTime : NSObject

@property(nonatomic,copy)NSString   *name;
@property(nonatomic,copy)NSString   *age;
@property(nonatomic,assign)BOOL     sex;
@property(nonatomic,strong)NSArray  *arrayFamlily;

- (NSDictionary *)cf_KeysWithValues;

@end

//ObjectRunTime.m实现文件

#import "ObjectRunTime.h"
#import <objc/runtime.h>

@implementation ObjectRunTime

- (NSDictionary *)cf_KeysWithValues {
    unsigned int count ,i;
    objc_property_t *propertyArray = class_copyPropertyList([self class], &count);
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];

    for (i = 0; i < count; i++) {
        objc_property_t property = propertyArray[i];
        NSString *proKey = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        id proValue = [self valueForKey:proKey];

        if (proValue) {
            [dic setObject:proValue forKey:proKey];
        } else {
            [dic setObject:@"" forKey:proKey];
        }
    }
    free(propertyArray);
    return dic;
}


@end
阅读更多

没有更多推荐了,返回首页