0

In my app the user has twelve buttons available, and I have defined twelve NSMutableArrays. If the user clicks button one, the app should count the number of objects in the Comp1 array, or if user clicks button two, the app should count the number of objects in the Comp2 array, and so on.

When user clicks a button, I save the name of the respective NSMutableArray in a NSString -- for example, myString = @"Comp1". My problem is, how do I "define" the NSMutableArray name with myString?

I wish there was a method like: [NSMutableArray arrayWithTitle:myString].

jscs
  • 63,694
  • 13
  • 151
  • 195
brunosfg
  • 3
  • 1
  • 1
    Create an array to hold your arrays. Possible duplicate of [Create multiple variables based on an int count](http://stackoverflow.com/q/2231783), [Syntax help: variable as object name](http://stackoverflow.com/q/7940809) [Is it possible to reference a variable with a string and an int?](http://stackoverflow.com/q/6049175) – jscs May 14 '13 at 19:00
  • 1
    What do you want to use the name for? Wouldn't it be enough to save a pointer to the array? – Marcin Kuptel May 14 '13 at 19:00

2 Answers2

4

Create a dictionary that holds the arrays. The dictionary key will be the title you're looking for.

For instance, insert button1's array to the dictionary, when you want to retrieve the count use:

NSInteger count = [myDictionary[@"Comp1"] count];
Sean Kladek
  • 4,396
  • 1
  • 23
  • 29
1

If the arrays are properties of some object (your view or view controller) you can use KVC to get it:

NSArray *myArray = [self valueForKey:myString];

But this is really bad practice. Why don't you put all your buttons into an array instead. Put your NSMutableArrays in a second array of same size. Then you can refer to them by index.

In your header:

@property (nonatomic) NSArray *buttons;
@property (nonatomic) NSArray *arrays;

In your implementation, after creating the buttons or loading them from a nib file (so this should probably go into either viewDidLoad or awakeFromNib):

self.button = @[button1, button2, button3 ... ];
self.arrays = @[array1, array2, array3 ... ];

Then, when the user taps a button:

- (IBAction)buttonTapper:(id)sender {
    UIButton *button = (UIButton *)sender;
    NSUInteger index = [self.buttons indexOfObject:button];
    NSMutableArray *theArray = [self.arrays objectAtIndex:index];
    // do something with the selected array.
}
DrummerB
  • 39,814
  • 12
  • 105
  • 142