0

Newbie question: Can one substitue commands, properties or methods for NSStrings or char at runtime?

Lets say I do something like this:

//these are the names of my properties of an NSObject I created
char theChangingProperty[17][18] = {"name", "title", "number", "property4", "property5", "property6", "property7", "property8", "property9", "property10", "property11", "property12", "property13", "property14", "property15", "property16", "property17"};

(PS I know there is a better actual objective-c way of getting an objects properties, I even found a post with this Get an object properties list in Objective-C)

anyway, how does one iterate through a list and have the property name change? Lets say I'm using dot notation at runtime during a loop... If I wanted to set 17 (or 100!) different properties of my object all to values of some other array all at once, like this:

for (int t=1; t<17; t++) {
    myObject.theChangingProperty[t] = valueOfAnotherArray[t];
}

I know objective-c is going to look for an actual property called "theChangingProperty". But I want that to be an array that will spit out the actual property that would change with each loop iteration (name, title, number, property4, etc)

Thanks for your time in answering a newbie question :)

Community
  • 1
  • 1
NSDestr0yer
  • 1,419
  • 16
  • 20

3 Answers3

3

What you want is called key-value coding. Specifically, the line you're trying to write is [myObject setValue:valueOfAnotherArray[t] forKey:[NSString stringWithUTF8String:theChangingProperty[t]]].

Chuck
  • 234,037
  • 30
  • 302
  • 389
2

Dot notation is resolved at compile time, not runtime, therefore you cannot use it for this purpose. You'll have to use the setter name for this. i.e., setTheChangingProperty: and performSelector: with the appropriate object to pass in as the value.

Note that in a simple case, this will probably work just fine, however, someone could have gone in and done something like:

@property (nonatomic, retain, setter=fooBarBaz:) id blurgle;

You in the above case, would not be simply able to assume setBlurgle: is the right setter.

jer
  • 20,094
  • 5
  • 45
  • 69
1

You can use setValue:forKey: but note that property keys need to be NSStrings, not C strings so declare your array:

NSString* theChangingProperty[17] = { @"name", ....

Then you would write:

for (int t = 0; t < 17; t++) 
{
    [myObject setValue: valueOfAnotherArray[t] forKey: theChangingProperty[t]];
}

Or you can use performSelector:withObject: but then your array needs to contain selectors

SEL theChangingProperty[17] = { @selector(setName:), ....

for (int t = 0; t < 17; t++) 
{
    [myObject performSelector: theChangingProperty[t] withObject: valueOfAnotherArray[t]];
}
JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • Thanks Jeremy, I ended up using something like [myObject setValue:[NSNumber numberWithInt:number] forKey:..... KVC was exactly what I was looking for, thanks! – NSDestr0yer Nov 15 '10 at 14:33