代码之家  ›  专栏  ›  技术社区  ›  Bill

如何在数组中存储uibuttons?

  •  1
  • Bill  · 技术社区  · 15 年前

    我有一个方法系在四个按钮上。我想创建一个包含每个按钮的数组,然后从数组中检索和交互w/a按钮。我在下面修改的代码。当我试图从数组中获取一个按钮并向它发送一条消息时,它会变得非常好。

    有没有想过我做错了什么?

    hack-dumpview控制器.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-dumpview控制器.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 回复  |  直到 15 年前
        1
  •  5
  •   Wevah    15 年前

    [NSArray arrayWithObjects:...] 返回一个自动释放的数组,因此当您使用它时,它已不存在,并且您最后会传递一个无效的指针。你想要的是 [[NSArray alloc] initWithObjects:...] (记得把它放在你的 dealloc )。

        2
  •  1
  •   fearmint    15 年前

    为什么不在Interface Builder中标记视图,然后像数组一样处理它们呢,这要容易得多