我在设备上测试应用程序时, [__ NSArrayM insertObject:atIndex:]:对象不能为崩溃,而不是在iOS模拟器上。
以下是发生的事情:
我在View Controller上管理5 UITextField
,然后我使用IBAction通过NSString
将每个UITextField的文本传递给另一个View Controller (当我按下按钮,它崩溃了。
TextViewController
- (IBAction)choicebutton:(id)sender {
AnswerViewController *AVC = [self.storyboard instantiateViewControllerWithIdentifier:@"AnswerViewController"];
AVC.stringFromChoice1 = self.choice1.text;
AVC.stringFromChoice2 = self.choice2.text;
AVC.stringFromChoice3 = self.choice3.text;
AVC.stringFromChoice4 = self.choice4.text;
AVC.stringFromChoice5 = self.choice5.text;
[self presentViewController:AVC animated:YES completion:nil];
}
然后在 AnswerViewController 上,我创建一个NSMutableArray
并随机化 NSStrings 以显示在UILabel
上。
AnswerViewController
- (void)viewDidLoad
{
self.choiceAnswers1 = [[NSMutableArray alloc] initWithCapacity:5];
if(![self.stringFromChoice1 isEqualToString:@""])
{
[self.choiceAnswers1 addObject:self.stringFromChoice1];
}
if(![self.stringFromChoice2 isEqualToString:@""])
{
[self.choiceAnswers1 addObject:self.stringFromChoice2];
}
if(![self.stringFromChoice3 isEqualToString:@""])
{
[self.choiceAnswers1 addObject:self.stringFromChoice3];
}
if(![self.stringFromChoice4 isEqualToString:@""])
{
[self.choiceAnswers1 addObject:self.stringFromChoice4];
}
if(![self.stringFromChoice5 isEqualToString:@""])
{
[self.choiceAnswers1 addObject:self.stringFromChoice5];
}
int index = arc4random() % [self.choiceAnswers1 count];
self.choiceanswer.text = self.choiceAnswers1[index];
self.choiceanswer1.text = self.choiceAnswers1[index];
}
如果用户没有填写所有的UITextFields,我会以这种方式设置它,这是否必须对崩溃做任何事情?我无法想出这个,请帮忙!
谢谢!
答案 0 :(得分:2)
不要对空字符串使用compare:
- 它不会捕获字符串为nil
而不是@“”
的情况。这是两个截然不同的案例。
而不是:
if(![self.stringFromChoice1 isEqualToString:@""])
{
[self.choiceAnswers1 addObject:self.stringFromChoice1];
}
使用它:
if (self.stringFromChoice1.length)
[self.choiceAnswers1 addObject:self.stringFromChoice1];
因为在C中任何非0值都为真,并且由于向nil对象发送消息总是返回0,因此捕获所有情况。并且不那么罗嗦。
更少的代码是更好的代码!
答案 1 :(得分:1)
将viewDidLoad更改为此类内容。
- (void)viewDidLoad
{
self.choiceAnswers1 = [[NSMutableArray alloc] init];
if(self.stringFromChoice1.length > 0)
{
[self.choiceAnswers1 addObject:self.stringFromChoice1];
}
if(self.stringFromChoice2.length > 0)
{
[self.choiceAnswers1 addObject:self.stringFromChoice2];
}
if(self.stringFromChoice3.length > 0)
{
[self.choiceAnswers1 addObject:self.stringFromChoice3];
}
if(self.stringFromChoice4.length > 0)
{
[self.choiceAnswers1 addObject:self.stringFromChoice4];
}
if( self.stringFromChoice5.length > 0)
{
[self.choiceAnswers1 addObject:self.stringFromChoice5];
}
int index = arc4random() % [self.choiceAnswers1 count];
self.choiceanswer.text = self.choiceAnswers1[index];
self.choiceanswer1.text = self.choiceAnswers1[index];
}
让我知道这有助于.. :))