2

I'm very new to this language, but have a good grasp of others.

I'm wondering how to dynamically access a field name property in objective c.

Something like:

self.bottomText.text = @"foo";

Going to:

NSString *bottomText = @"bottomText";

self[bottomText].text = @"foo";

I can understand how it would be possible to set the property like this (as per the duplication mark below):

[self setValue:value forKey:@"propertyName"];

But it seems to me that either it would have to be along the lines of:

[self.bottomText setValue:@"foo" forKey:@"text"];

Which doesn't really solve the problem, or something like:

[self setValue:bottomText forKey:property].text = @"foo";

Not knowing what property is.

Or maybe:

[self valueForKey:bottomText].text = @"Test";

But no love.

Super-confused on this one.

Jesse James Richard
  • 473
  • 1
  • 6
  • 20
  • 1
    @Drew I disagree. Using comments to post things one has tried, ideas that haven't worked, or any information directly related to the question should be *discouraged*. If I saw something like that in a comment, I'd probably post a comment saying it should be added to the question. In any case, I'm voting to reopen. It's related to the linked post but it's not a duplicate. – Adi Inbar Nov 20 '15 at 18:54
  • fair enough. Just mark it as *Edit: * for post-closed attempts – Drew Nov 20 '15 at 18:57

2 Answers2

1

Well, assuming bottomText is a UILabel (since it has a text property...), you could do something like this:

SEL selector = NSSelectorFromString(@"bottomText");
UILabel *label = (UILabel *)[self performSelector:selector];
label.text = @"Test";

or if you really want it in one line:

[(UILabel *)[self performSelector:NSSelectorFromString(@"bottomText")] setText:@"Test"];
Marcos Crispino
  • 8,018
  • 5
  • 41
  • 59
1

I'm pretty unsure, whether I did understand your Q correct. But simle KVC should solve your problem:

NSString *bottomText = @"bottomText";
[self valueForKey:bottomText].text = @"foo";

or

NSString *property = @"bottomText.text";
[self setValue:@"foo" forKeyPath:property];

Additionally the class of self could implement keyed subscription.

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50