簡體   English   中英

UIButtons數組返回錯誤

[英]Array of UIButtons return error

我有一個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);
}

請幫我哪里錯了。

首先從數組屬性的聲明中刪除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文件,則:

另一種方法是將UIButtons連接到Interface Builder中的IBOutletCollectionNSArray ,而不是將每個按鈕手動添加到NSMutableArray 所有UIButton都類似這樣。

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

Xcode

只需更改一下代碼即可。

替換此行:

@property NSMutableArray *_starButtons;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM