1

I have a method tied to four buttons. I want to create an array containing each button, and later retrieve and interact w/ a button from the array. The code I was tinkering with below. When I try to get a button from the array and send it a message, it goes kablooie.

Any thoughts on what I'm doing wrong?

Hack_DumpViewController.h

#import <UIKit/UIKit.h>

@interface Hack_DumpViewController : UIViewController {
    IBOutlet UIButton *redButton;
    IBOutlet UIButton *greenButton;
    IBOutlet UIButton *blueButton;
    IBOutlet UIButton *yellowButton;    
    NSArray *buttonMapping; 
}

- (IBAction) changeToYo:(id)sender;
@property (nonatomic, retain) UIButton *redButton;
@property (nonatomic, retain) UIButton *greenButton;
@property (nonatomic, retain) UIButton *blueButton;
@property (nonatomic, retain) UIButton *yellowButton;
@property (nonatomic, retain) NSArray *buttonMapping;   


@end

Hack_DumpViewController.m

#import "Hack_DumpViewController.h"

@implementation Hack_DumpViewController

@synthesize redButton;
@synthesize greenButton;
@synthesize yellowButton;
@synthesize blueButton;
@synthesize buttonMapping;

- (IBAction) changeToYo:(id)sender {
    NSLog(@"changing numbers!");
    for (UIButton *b in buttonMapping) {
        [b setTitle:@"yo!"];
    }
    NSLog(@"changed to numbers!");
}


- (void)viewDidLoad {
buttonMapping = [[NSArray alloc] initWithObjects:greenButton, redButton, yellowButton, blueButton, nil];    
}
Toby Allen
  • 10,997
  • 11
  • 73
  • 124
Bill
  • 3,584
  • 5
  • 35
  • 47
  • Updated to incorporate Wevah's fix to alloc the NSArray. The problem is that the call to [b setTitle...] is still unhappy. – Bill Oct 24 '09 at 04:19
  • Ah, turns out I wasn't stating 'forState:UIControlStateNormal'. – Bill Oct 25 '09 at 05:28

2 Answers2

5

[NSArray arrayWithObjects:...] returns an autoreleased array, so by the time you use it, it no longer exists and you end up messaging an invalid pointer. What you want is [[NSArray alloc] initWithObjects:...] (remembering to release it in your dealloc).

Wevah
  • 28,182
  • 7
  • 83
  • 72
  • Thanks! It now gets into the for loop, but it still doesn't like it when I try to send b a message. :( – Bill Oct 24 '09 at 03:53
1

Why not tag the views in interface builder and then treat them like an array, much easier

fearmint
  • 5,276
  • 2
  • 33
  • 45
  • 2
    I think he means giving each button a tag from 0 through 3 and then just using a standard `for` loop (I prefer direct references, but this method should work, too). – Wevah Oct 24 '09 at 03:58