2017-05-04 45 views
0

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

“终止应用程序由于未捕获的异常 '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); 
} 

请hel我在哪里我错了。

+0

这行是你得到的错误? –

+0

尝试将NSMutableArray属性更改为强而不是副本。 –

+1

@Imad我已经改变了复制到它强给我 'NSInvalidArgumentException',原因:'*** - [__ NSArrayM insertObject:atIndex:]:object can not be nil' – diksha

回答

1

先从数组属性声明中删除copy,使其为strong

第二件事,正如你在评论中所说,你已经编程创建了按钮,那么你不需要IBOutlets。因此,请从按钮的所有属性中删除IBOutlets。如果你使用故事板或再NIB文件

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

} 
+0

这不一定是正确的解决方案。原来的属性使用'copy'。据推测,这有一个很好的理由。简单地删除'copy'会改变行为,并可能导致很难注意到错误。 – rmaddy

+0

根据问题发布的代码,我不认为'复制'是必需的! @rmaddy – Lion

0

试试这个Interface Builder中的NSArrayIBOutletCollection,而不是手动将每个按钮添加到NSMutableArray。对于所有的UIButtons都是这样的'。

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

Xcode

0

另一种方法是将UIButtons'连接到

你的宣言谨

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

在代码只是一个变化。

替换此行:

@property NSMutableArray *_starButtons;