views:

214

answers:

2

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]; 
}
+3  A: 

[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
Thanks! It now gets into the for loop, but it still doesn't like it when I try to send b a message. :(
Bill
A: 

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

JoePasq
Can you elaborate?
Bill
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