我有一组UIButton
个对象(我有5个按钮,所以我想将它们存储在一个数组中以便于处理)。但是Array
给了我错误
“因未捕获的异常而终止应用 'NSInvalidArgumentException',原因:' - [__ NSArray0 addObject:]: 无法识别的选择器发送到实例“
@property (weak, nonatomic) IBOutlet UIButton *starOne;
@property (weak, nonatomic) IBOutlet UIButton *starTwo;
@property (weak, nonatomic) IBOutlet UIButton *starThree;
@property (weak, nonatomic) IBOutlet UIButton *starFour;
@property (weak, nonatomic) IBOutlet UIButton *starFive;
@property (nonatomic, copy) NSMutableArray *_starButtons;
我在viewDidLoad
方法
- (void)viewDidLoad {
self._starButtons=[[NSMutableArray alloc]init];
[self._starButtons addObject:self.starOne];
[self._starButtons addObject:self.starTwo];
[self._starButtons addObject:self.starThree];
[self._starButtons addObject:self.starFour];
[self._starButtons addObject:self.starFive];
NSLog(@"%@",self._starButtons);
}
请在我出错的地方帮助我。
答案 0 :(得分:1)
首先从数组属性的声明中删除copy
,将其设为strong
。
第二件事,如您在评论中说过,您已经以编程方式创建了按钮,那么您不需要IBOutlets
。因此,请从按钮的所有属性中删除IBOutlets
。
你的声明应该是,
@property (weak, nonatomic) UIButton *starOne;
@property (weak, nonatomic) UIButton *starTwo;
@property (weak, nonatomic) UIButton *starThree;
@property (weak, nonatomic) UIButton *starFour;
@property (weak, nonatomic) UIButton *starFive;
@property (nonatomic, strong) NSMutableArray *_starButtons;
答案 1 :(得分:0)
试试这个:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *one;
@property (weak, nonatomic) IBOutlet UIButton *two;
@property (weak, nonatomic) IBOutlet UIButton *three;
@end
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *buttonArray = [[NSMutableArray alloc] initWithObjects:one,two,three,nil];
NSLog(@"%@",buttonArray);
}
答案 2 :(得分:0)
如果您正在使用Storyboard或Nib文件,那么:
另一种方法是将UIButtons'连接到Interface Builder中的NSArray
IBOutletCollection
,而不是手动将每个按钮添加到NSMutableArray
。对于所有UIButton来说都是这样的。
@property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *buttonsArray;
答案 3 :(得分:0)
代码只需更改一次。
替换此行:
@property NSMutableArray *_starButtons;