iOS反射的基本应用
来源:互联网 发布:win8 ubuntu 编辑:程序博客网 时间:2024/04/29 07:28
导入头文件 #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;
}
0 0
- iOS反射的基本应用
- 反射的基本应用
- Java_反射的基本应用
- java反射基本应用
- JDK工具类_____反射的基本应用
- Java反射的基本应用——代码详解
- iOS中WebView的基本应用
- iOS中时间日期的基本应用
- 反射的基本调用
- 反射的基本API
- 反射的基本使用
- 反射的基本使用
- 反射的基本使用
- 反射的基本用法
- 反射的基本使用
- 反射的基本使用
- Java Reflect(反射一) 基本应用
- 反射的简单应用
- Objective-C——类别(Category)详解
- LINUX下动态链接库的使用-dlopen dlsym dlclose dlerror
- Hibernate.cfg.xml配置文件结构详解
- Couldn't load jpush181 from loader dalvik.system.PathClassLoader
- windows的inf
- iOS反射的基本应用
- wordpress注册加上问题验证
- public类和友好类
- JavaScript高级程序设计之DOM 扩展之HTML5之插入标记第11.3.6讲
- 笔记_Maya绑定基础_骨骼连接工具,以及修改和删除多余骨骼工具
- Java 数据结构原理分析
- Week2-3Text similarity:introduction
- RGB颜色与16进制色以及透明色
- 手势action_block