如何将UIButton存储在数组中?

时间:2009-10-24 00:34:22

标签: iphone objective-c

我有一个方法绑定到四个按钮。我想创建一个包含每个按钮的数组,然后检索并与数组中的按钮进行交互。我在下面修补的代码。当我尝试从阵列中获取一个按钮并向其发送消息时,它会变成kablooie。

对我做错了什么的想法?

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];    
}

2 个答案:

答案 0 :(得分:5)

[NSArray arrayWithObjects:...]返回一个自动释放的数组,所以当你使用它时,它不再存在,你最终会传递一个无效的指针。你想要的是[[NSArray alloc] initWithObjects:...](记得在你的dealloc中发布它。)

答案 1 :(得分:1)

为什么不在界面构建器中标记视图,然后将它们视为数组,更容易