0

Possible Duplicate:
Objective C Equivalent of PHP’s “Variable Variables”

Today in one of my classes I learned you can access a variable by building its name from a string in Actionscript 3.0, like so:

var star1:symbol;
var star2:symbol;
var star3:symbol;
var star4:symbol;

for(i=1; i <= 4; i++)
    [this "star" + i].method = something

This gets star1, then star2, then star3, then star4, and does some method with them.

Is there a way to do something like this in Objective-C?

Community
  • 1
  • 1
AGleasonTU
  • 2,775
  • 2
  • 14
  • 12
  • don't you mean this["star"+i].method – The_asMan Oct 16 '12 at 17:50
  • possible duplicate of [ObjC equivalent of PHP's "Variable Variables"](http://stackoverflow.com/questions/2283374/objective-c-equivalent-of-phps-variable-variables), [Create multiple variables based on an int count](http://stackoverflow.com/questions/2231783/create-multiple-variables-based-on-an-int-count/), [Syntax help: variable as object name](http://stackoverflow.com/questions/7940809/syntax-help-variable-as-object-name) – jscs Oct 16 '12 at 17:58

3 Answers3

3

Not quite as neat, but key-value coding does that:

[self setValue:something forKey:[NSString stringWithFormat:@"star%u", i]]

EDIT: on reflection it's unclear as a non-Actionscript user whether you intend to access properties or call methods.

You'd use NSSelectorFromString to convert the name of a method into a selector at runtime, then [self performSelector:...] to call the thing if it's the latter.

Tommy
  • 99,986
  • 12
  • 185
  • 204
1

Yes. Use an NSArray. Then you can do something like this:

NSArray *array = [NSArray arrayWithObjects:obj1, obj2, obj3, obj4, nil];
for (int i = 0; i < [array count]; i++) {
    [[array objectAtIndex:i] doMethod];
}

Or even easier:

NSArray *array = [NSArray arrayWithObjects:obj1, obj2, obj3, obj4, nil];
for (id obj in array) {
    [obj doMethod];
}
mipadi
  • 398,885
  • 90
  • 523
  • 479
0

No, but you can put the variables in an array and achieve the same that way.

driis
  • 161,458
  • 45
  • 265
  • 341