0

I have some code like this:

 for(int i = 0; i<5; i++) {

        self.objecti = someObject;

    }

I want to select an object based on i, so if i=1 then my code executes self.object1=someObject; Is it possible to create a string of the object name and then access it this way?

Kex
  • 8,023
  • 9
  • 56
  • 129
  • 1
    what is object1 and someObject ? – iOSNoob Feb 11 '15 at 07:14
  • 1
    That is just a general example. In my app I want to modify UIButtons based on the loop. I can't use an array either. – Kex Feb 11 '15 at 07:17
  • Try to tag your buttons and make changes as per condition like if(i==0){ //code } as shown in below answer. – iOSNoob Feb 11 '15 at 07:19
  • 1
    Any time you find yourself with objects like `label1`, `label2`, `label3`, etc., you should just have an array of labels instead. – Aaron Brager Feb 11 '15 at 07:21
  • so should I put all the labels and buttons in separate arrays? – Kex Feb 11 '15 at 07:22
  • Separate arrays should work fine. If you really want to keep the combinations of button and label, you can also use an array of dictionaries for this. Each dictionary can contain a label/button combination. – Aaganrmu Feb 11 '15 at 08:38

2 Answers2

4

This is possible using Key Value Coding, as explained in the first answer to this question:

for(int i = 0; i<5; i++) {
    [self setValue:someObject forKeyPath:[NSString stringWithFormat:@"object%i", i];
}
Community
  • 1
  • 1
Aaganrmu
  • 328
  • 1
  • 11
0

You can try like this,

for(int i = 0; i<5; i++) 
{
  if(i==0)
   {
    self.yourString = [NSString stringWithFormat:@"%@",array[i]];
   }
}
iOSNoob
  • 1,420
  • 2
  • 16
  • 30