我在程序中需要用到一个反射 我又一个有两百多个属性的实体,在服务器传输数据到客户端的时候我需要把数据 转换成实体,我有多个实体,所以我写了一个通用的反射方法 把一个NSdictionary 转换成实体 但是这个过程需要的时间太长啦,转换5000个实体需要花费1分半的时间, 有没有大神可以优化下,把时间缩短到半分钟之内!

解决方案 »

  1.   

    我转化的方法是这样的:+ (void)initWithDictionary:(NSDictionary *)dict convertClass:(id __autoreleasing *)convertClass;
    {
        id objc = *convertClass;
        @autoreleasepool {
            unsigned int outCount, i;
            objc_property_t *properties = class_copyPropertyList([objc class], &outCount);
            for (i = 0; i<outCount; i++)
            {
                objc_property_t property = properties[i];
                const char* char_f =property_getName(property);
                NSString *propertyName = [[NSString alloc] initWithUTF8String:char_f];
                id propertyValue = [objc valueForKey:propertyName];
                
                id value = [[dict objectForKey:propertyName] copy];
                
                //判断要转化的数据是否为空 (判断数据类型)
                if (([[NSString stringWithFormat:@"%@", [propertyValue class]] isEqualToString:@"__NSCFNumber"] ||
                    [[NSString stringWithFormat:@"%@", [propertyValue class]] isEqualToString:@"__NSCFBoolean"]) &&
                    value == nil) {
                    value = [NSNumber numberWithInteger:0];
                } else if (propertyValue == nil && value == nil) {
                    value = @"";
                } else if (![[NSString stringWithFormat:@"%@", [value class]] isEqualToString:@"__NSCFNumber"] &&
                           ![[NSString stringWithFormat:@"%@", [value class]] isEqualToString:@"__NSCFBoolean"] &&
                           value != nil &&
                           [value isKindOfClass:[NSNull class]])
                {
                    value = @"";
                }
                
                [objc setValue:value forKey:propertyName];
            }
        }
    }