iOS反射的基本应用

时间:2021-12-21 19:19:14
 导入头文件 #include <objc/runtime.h>
        #pragma mark 获取类型的名称        Class clsName = [Student class];        const char * cName = class_getName(clsName);        NSString *className = [NSString  stringWithCString:cName encoding:NSUTF8StringEncoding];        NSLog(@"className = %@",className);                #pragma mark 获取父类的类型的名称        Class clsP = [PrimarySchoolStudents class];        Class superClass = class_getSuperclass(clsP);        NSString *superName = [NSString  stringWithCString:class_getName(superClass) encoding:NSUTF8StringEncoding];        NSLog(@"superName = %@",superName);                        #pragma mark 取出每一个属性的值 - 对象转化成字典        Student *student = [Student new];        student.name = @"张三";        student.age =@20;        student.number= @123456;        NSMutableDictionary *stuDict = [NSMutableDictionary dictionaryWithCapacity:1];        unsigned int outCount ;        objc_property_t *properties = class_copyPropertyList([student class], &outCount);        for (int i = 0; i < outCount; i++) {            objc_property_t property = properties[i];            NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];            id val = [student valueForKey:propertyName];//kvc取值            [stuDict setObject:val forKey:propertyName];//将值放到相应的字典里面        }        NSLog(@"PropertyCount = %d",outCount);                #pragma mark 将字典转化为对象        Student *stu = [Student new];        for (NSString *key  in stuDict.allKeys) {            id val = [stuDict objectForKey:key];            [stu setValue:val forKey:key];//kvc赋值        }        NSLog(@"%@",stu.name);



插一段神奇的代码: 

-(id) initWithDict:(NSDictionary*) dict

{

    self = [superinit];

    if (self) {

        [selfsetValuesForKeysWithDictionary:dict];//j就是这个 直接一步将字典恰好完全转化成对象   不需要遍历属性 然后 kvc赋值了

    }

    returnself;

}