Search code examples
cocoansbutton

naming a number of NSButtons


I have written some terrible code but it works. Is there a better way to write this? _decade.x are NSButtons.

int baseDecade = 1940;
NSString *title;
int currentDecade = 0;

- (IBAction)nameDecade:(id)sender {

    currentDecade = baseDecade;
    title = [NSString stringWithFormat: @"%ld", (long)currentDecade];
    _decade1.stringValue = title;

    currentDecade = currentDecade +10;
    title = [NSString stringWithFormat: @"%ld", (long)currentDecade];
    _decade2.stringValue = title;

    currentDecade = currentDecade +10;
    title = [NSString stringWithFormat: @"%ld", (long)currentDecade];
    _decade3.stringValue = title;

Solution

  • In iOS you can put your buttons in a single IBOutletCollection in interface builder, or in an NSArray if you create your buttons through code. With that outlet collection / array in hand, you can use a loop to reference _decadeN by their index in the collection:

    @property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *decadeButtons;
    ...
    for (int i = 0 ; i != decadeButtons.count ; i++) {
        UIButton * decade = decadeButtons[i];
        NSString *title = [NSString stringWithFormat: @"%ld", (long)(baseDecade+10*i)];
        decade.stringValue = title;
    }
    

    Edit: OSX does not support IBOutletCollections yet, so you would need to put _decadeN buttons in an array namually:

    // I am using the new array literal syntax; using arrayWithObjects will work too.
    NSArray *decadeButtons = @[_decade1, _decade2, _decade3];
    // Use the same loop as above:
    for (int i = 0 ; i != decadeButtons.count ; i++) {
        UIButton * decade = decadeButtons[i];
        NSString *title = [NSString stringWithFormat: @"%ld", (long)(baseDecade+10*i)];
        decade.stringValue = title;
    }