UIButton 数组 return 错误

Array of UIButtons return error

我有一个 UIButton 对象数组(我有 5 个按钮,所以我想将它们存储在一个数组中以便于处理)。但是 Array 给我错误

"Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArray0 addObject:]: unrecognized selector sent to instance"

@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);
}

请帮我看看我错在哪里。

首先从数组 属性 的声明中删除 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;

试试这个:

@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);

}

如果您使用的是 Storyboard 或 Nib 文件,则:

另一种方法是在 Interface Builder 中将 UIButtons 连接到 IBOutletCollectionNSArray,而不是手动将每个按钮添加到 NSMutableArray。对于所有 UIButton 都是这样的。

@property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *buttonsArray;

只需更改一处代码。

替换此行:

@property NSMutableArray *_starButtons;