您的位置:首页 > 移动开发 > Objective-C

【OBJC类扩展之属性字典】NSObject+Property

2016-06-16 09:24 393 查看
#import <Foundation/Foundation.h>

#import <objc/runtime.h>

@interface NSObject (Property)

//将对象属性封装到字典,并返回字典

-(NSDictionary *)propertyDictionary;

@end

@implementation NSObject (Property)

-(NSDictionary *)propertyDictionary

{

    //创建可变字典

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];

    unsigned int outCount;

    objc_property_t *props = class_copyPropertyList([self class], &outCount);

    for(int i=0;i<outCount;i++){

        objc_property_t prop = props[i];

        NSString *propName = [[NSString alloc]initWithCString:property_getName(prop) encoding:NSUTF8StringEncoding];

        id propValue = [self valueForKey:propName];

        if(propValue){

            [dict setObject:propValue forKey:propName];

        }

    }

    free(props);

    return dict;

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: