zoukankan      html  css  js  c++  java
  • iOS反射机制:objc_property_t的使用

    #import <objc/runtime.h>

     需要导入这个头文件。

    • 动态获取一个自定义类对象中的所有属性
      - (NSDictionary *)allProperties
      {
          NSMutableDictionary *props = [NSMutableDictionary dictionary];
          unsigned int outCount, i;
          objc_property_t *properties = class_copyPropertyList([self class], &outCount);
          for (i = 0; i<outCount; i++)
          {
              objc_property_t property = properties[i];
              const char *char_f =property_getName(property);
              NSString *propertyName = [NSString stringWithUTF8String:char_f];
              id propertyValue = [self valueForKey:(NSString *)propertyName];
              if (propertyValue)
                  [props setObject:propertyValue forKey:propertyName];
          }
          free(properties);
          return props;
      }
      
    • 实现对象的自动赋值
      - (BOOL)reflectDataFromOtherObject:(NSObject*)dataSource
      
      {
          BOOL ret = NO;
          //propertyKeys 其实就是上面的方法的变形,上面方法回传一个可变字典,这里是得到一个可变数组的一个处理
          for (NSString *key in [self propertyKeys])
          {
          if ([dataSource isKindOfClass:[NSDictionary class]])
            {
          ret = ([dataSource valueForKey:key]==nil)?NO:YES;
            }
          else
            {
          ret = [dataSource  respondsToSelector:NSSelectorFromString(key)];
            }
          if (ret)
            {
          id propertyValue = [dataSource valueForKey:key];
          //该值不为NSNULL,并且也不为nil
          if (![propertyValue isKindOfClass:[NSNull class]] && propertyValue!=nil)
               {
          [self setValue:propertyValue forKey:key];
               }
             }
          }
      return ret;
      }
      
  • 相关阅读:
    Math Jax开源数学编辑器的使用
    阿里云pai项目使用说明
    tomcat管理授权:tomcat-users.xml
    NoSQLBooster for MongoDB的基本使用
    IDEA的配置文件访问
    task
    Netty基础点滴
    二星权限树的设计与实现
    easyui实现树形菜单Tab功能、layout布局
    如何用Dome4j(2.2.1)创建Xml
  • 原文地址:https://www.cnblogs.com/fuunnyy/p/5711355.html
Copyright © 2011-2022 走看看