runtime使用小例子 - 给对象O-C属性赋值

时间:2023-03-09 01:58:53
runtime使用小例子 - 给对象O-C属性赋值

这些日子在家里学习runtime,看runtime的一些方法和前辈们的博客,我也尝试着写几个runtime有效的运用

一、给对象属性赋值,例如一个WebEntity类

她有三个属性:NSString、NSInteger

#import "WebEntity.h"  // 假设是一个网络数据返回实体类

@interface WebEntity ()
@property (nonatomic, strong) NSString *string;  // O-C字符串类
@property (nonatomic, assign) NSInteger number;  // NSInteger类型
@end

运用runtime来给property赋值

1》Responsed数据类型假设是NSDictionary类型:

NSDictionary * responsedData =  @{

                                      };

2》赋值函数

public:

/**
 *  model赋值
 *
 *  @param instance 被赋值的instance对象
 *  @param params   赋值的params参数
 */
- (void)setDataForKeyWithInstance:(id)instance params:(NSDictionary *)params
{
    [params enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop)
    {
        if ([self checkIsExistPropertyWithInstance:instance verifyPropertyName:key])
        {
            [instance setValue:obj forKey:key];
        }
    }];
}

private:

/**
 *  检查对象中是否有制定属性名
 *
 *  @param instance           被检查的对象
 *  @param verityPropertyName 检查的属性名称
 *
 *  @return 检查有无返回值,有YES反之NO
 */
- (BOOL)checkIsExistPropertyWithInstance:(id)instance verifyPropertyName:(NSString *)verityPropertyName
{
    unsigned int outCount , i ;

    objc_property_t * properties = class_copyPropertyList([instance class], &outCount);
    ; i < outCount; i++)
    {
        objc_property_t property = properties[i];
        NSString * propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        if ([propertyName isEqualToString:verityPropertyName])
        {
            free(properties);
            return YES;
        }
    }
    free(properties);
    return NO;
}

3》代码应用:

WebEntity * entity = [WebEntity new];

NSDictionary * responsedData =  @{

@"string":@"字符串类型",

@"number":@5

};

[self setDataForKeyWithInstance:entity params:responsedData];

NSLog(@"%@ - %d",entity.string,entity.number);

结果:

-- :::] 字符串类型 - 

bwy:

目前支持的是O-C的数据类型 NSDictionary、 NSArray、等