如何将UIButtons存储在数组中

如何将UIButtons存储在数组中

本文介绍了如何将UIButtons存储在数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法绑定到四个按钮.我想创建一个包含每个按钮的数组,以后再从该数组中检索和交互一个按钮.我在下面修改的代码.当我尝试从数组中获取一个按钮并向其发送消息时,它就会变成kablooie.

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

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

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

推荐答案

[NSArray arrayWithObjects:...] 返回一个自动释放的数组,因此当您使用它时,它不再存在并且您最终会向消息传递无效的指针.您想要的是 [[NSArray alloc] initWithObjects:...] (记住要在您的 dealloc 中释放它).

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

这篇关于如何将UIButtons存储在数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 12:03