简体   繁体   English

如何引用Objective-C类属性?

[英]How to reference to a Objective-C class attribute?

I'm developing an application that have views with a lot of fields. 我正在开发一个具有很多字段视图的应用程序。 I have been manipulating them one by one because I don't know how to reference class attributes to be able to dynamically save them. 我一直在逐个操作它们,因为我不知道如何引用类属性来动态保存它们。

Right now I have a lot of line of codes to manipulate a single field... For example: 现在我有很多代码来操作单个字段...例如:

self.rowField.delegate = self;

NSArray *collectionNames = @[@"personTypeCategories", @"personTypes", @"genders", @"rows", @"seats", @"seatingOthers", @"restraintSystems", @"helmetUses"];

if ([collectionName isEqualToString:@"personTypeCategories"]) {
    [self loadDefaultForCollection:@"personTypeCategories" toField:self.personTypeCategoryField withKey:@"PersonTypeCategoryID" defaultValue:self.editingPerson.typeCategoryKey];
}

if (textField == self.rowField) {
    [self showCollection:@"rows" withIDColumn:@"RowID" withField:textField];
    return NO;
} 

When I have a new field that follow our standard of saving information and later posting it to the server I need to create this lines for each one and now I want to do it dynamically by creating an array like this: 当我有一个符合我们保存信息标准的新字段,然后将其发布到服务器时,我需要为每个字段创建这些行,现在我想通过创建这样的数组来动态地创建它:

- (void)loadViewConfiguration {
    self.viewElements = [[NSMutableArray alloc] init];

    [self.viewElements addObject:@{
        @"restMethod" : @"personTypeCategories",
        @"key" : @"PersonTypeCategoryID",
        @"field" : self.personTypeCategoryField,
        @"enabled" : @YES,
        @"modelAttr" : &self.editingPerson.typeCategoryKey
    }];
}

The problem is in the modelAttr, I need to have that class attribute reference in order to later go and modify or get it. 问题出在modelAttr中,我需要有类属性引用,以便以后去修改或获取它。

Another option could be if I can dynamically call class attributes like you can do in PHP, for example: 另一种选择可能是我可以像在PHP中那样动态调用类属性,例如:

$attr = "name";
$editingPerson->{$attr} = "Omar";

Thanks for the help. 谢谢您的帮助。

I didn't know you can use key-value coding for this purpose. 我不知道你可以为此目的使用键值编码。

To accomplish this what I did is to simply save the name of the attribute and later get the value by using: 为了实现这一点,我所做的只是保存属性的名称,然后通过使用以下方式获取值:

[classInstance valueForKey:elem[@"modelAttr"]];

An example of this: 一个例子:

for (NSDictionary *elem in self.viewElements) {
       if ([collectionName isEqualToString:elem[@"restMethod"]]) {
                [self loadDefaultForCollection:elem[@"restMethod"] toField:elem[@"field"] withKey:elem[@"key"] defaultValue:[self.editingPerson valueForKey:elem[@"modelAttr"]]];
       }
}

Thanks for the advice by @matt 感谢@matt的建议

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM