开发者

How can I store UIButtons in an array?

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开发者_如何学JAVA 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];    
}


[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).


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜