如何将UIButton存储在数组中?

Bil*_*ill 1 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
Run Code Online (Sandbox Code Playgroud)

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];    
}
Run Code Online (Sandbox Code Playgroud)

Wev*_*vah 5

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