7

In PHP and in JavaScript you can dynamically use a variable by using another variable as part of its name. I do not want to use an array as part of the solution. Can this be achieved in Objective C? I'd like to do something like this:

for (int i=1; i<6; i++) {
        if([appRecord.answer(i) length] != 0){
            self.textView.answer(i)ViewSingle.text = appRecord.answer(i);
        }
}
james_womack
  • 10,028
  • 6
  • 55
  • 74
  • 2
    Same question: http://stackoverflow.com/questions/2231783/create-multiple-variables-based-on-an-int-count/2231839#2231839 Not saying you'll like the answer, but there it is. Use an array. – Chuck Feb 17 '10 at 18:34
  • I think the questions are similar but not the same. The answer is the same though, of course. – Rob Keniger Feb 18 '10 at 00:01
  • How could this question be a duplicate of another question that was asked more than a year after this one? Oh moderators... – james_womack Jul 01 '16 at 19:27

2 Answers2

21

Short answer: No.

Long answer: Kind of.

  1. You can use an array, store your variables in there, and index into it.
  2. Like #1, if your objects are actually UI elements and you don't want a whole bunch of IBOutlets, then use an IBOutletCollection instead.
  3. You can use a dictionary, store your variables as values, and look them up by key.
  4. You can declare all your variables as @property, and then use [self valueForKey:] to look them up by name.
  5. You can build the name of the ivar as a string, and then use something like object_getInstanceVariable() to retrieve it's value directly (this is similar to #3, except you don't have to declare it as an @property). This is excessively complicated and is usually a much bigger hammer than you'll actually need.
  6. If you're dealing with views, you can assign each view a unique tag and then retrieve it via [superview viewWithTag:aTag]. I do not recommend using this approach.

EDIT: Note that this only works with instance variables. This does not work with global/static variables.

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
  • 1
    Wow, [self valueForKey:] was exactly what I needed as all of the variables I need were already declared using @property. object_getInstanceVariable may work as well, but I'm not sure yet. You have offered by far the best answer on this topic on the internet. – james_womack Feb 17 '10 at 20:00
  • @Cirrostratus - glad to help. I would use `object_getInstanceVariable()` as a second or third option. `valueForKey:` is probably the best way to go. – Dave DeLong Feb 17 '10 at 22:02
0

No. But you can give a tag to the view and use -viewWithTag:.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005