使用反射设置Objective-C类的属性值 [英] Set property values of an Objective-C class using reflection

查看:143
本文介绍了使用反射设置Objective-C类的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习Objective-C中的反思.我找到了一些有关如何转储类的属性列表的重要信息,尤其是在此处,但是我想知道如果可以使用反射来设置属性的值.

I am trying to learn reflection in Objective-C. I've found some great information on how to dump the property list of a class, especially here, but I want to know if it is possible to set a property's value using reflection.

我有一个键(属性名称)和值(所有NSString s)的字典.我想使用 Reflection 来获取属性,然后将其值设置为字典中的值.这可能吗?还是我在做梦?

I have a dictionary of keys (property names) and values (all NSStrings). I want to use Reflection to get the property and then set its value to the value in my dictionary. Is this possible? Or am I dreaming?

这与字典无关.我只是在使用字典来发送值.

This has nothing to do with the dictionary. I am merely using the dictionary to send in the values.

类似于此问题,但针对目标C.

Like this question, but for Objective C.

- (void)populateProperty:(NSString *)value
{
    Class clazz = [self class];
    u_int count;

    objc_property_t* properties = class_copyPropertyList(clazz, &count);
    for (int i = 0; i < count ; i++)
    {
        const char* propertyName = property_getName(properties[i]);
        NSString *prop = [NSString  stringWithCString:propertyName encoding:NSUTF8StringEncoding]];
        // Here I have found my prop
        // How do I populate it with value passed in?
    }
    free(properties);

}

推荐答案

目标C属性自动符合NSKeyValueCoding协议.您可以使用setValue:forKey:通过字符串属性名称设置任何属性值.

Objective C properties automatically conform to the NSKeyValueCoding protocol. You can use setValue:forKey: to set any property value by a string property name.

NSDictionary * objectProperties = @{@"propertyName" : @"A value for property name",
                                    @"anotherPropertyName" : @"MOAR VALUE"};

//Assuming class has properties propertyName and anotherPropertyName
NSObject * object = [[NSObject alloc] init];

for (NSString * propertyName in objectProperties.allKeys)
{
    NSString * propertyValue = [objectProperties valueForKey:propertyName];

    [object setValue:propertyValue
              forKey:propertyName];
}

这篇关于使用反射设置Objective-C类的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆