简体   繁体   English

[NSMutableArray insertObject:atIndex:]: 尝试在 0' 处插入 nil object

[英][NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 0'

i am creating custom cell.我正在创建自定义单元格。

In that i added 3 textfields.在那我添加了 3 个文本字段。 so i want to store that textfield values into nsmutablearray.所以我想将该文本字段值存储到 nsmutablearray 中。

when i am trying this code当我尝试这段代码时

UITextField *valueField = [[UITextField alloc] initWithFrame:CGRectMake(165,6, 135, 30)];
valueField.borderStyle =  UITextBorderStyleRoundedRect;
[cell addSubview:valueField];
[array1 addObject:valueField.text];
[valueField release];

i am getting error like this我收到这样的错误

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 0'

so please tell me the reason thanks in advance.所以请告诉我原因提前谢谢。

Just add this condition to check if the textfield is empty (ie textfield.text = nil):只需添加此条件以检查文本字段是否为空(即 textfield.text = nil):

if (valueField.text != nil) {
     [array1 addObject:valueField.text];
}
else {
     [array1 addObject:@""];
}

This will check if textfield is empty it will add an empty string.这将检查文本字段是否为空,它将添加一个空字符串。 If you dont want that just skip the else part.如果您不希望这样,请跳过其他部分。

The text attribute of UITextField is nil by default. UITextField的text属性默认为nil。 Set it to an empty string before adding it to your array, though I think this is not what you are trying to achieve.在将其添加到数组之前将其设置为空字符串,尽管我认为这不是您想要实现的目标。

UITextField *valueField = [[UITextField alloc] initWithFrame:CGRectMake(165,6, 135, 30)];
valueField.borderStyle =  UITextBorderStyleRoundedRect;
valueField.text = @"";
[cell addSubview:valueField];
[array1 addObject:valueField.text];
[valueField release];

the above code will work fine for you.上面的代码很适合你。

I noticed you said you declared your array like so:我注意到你说你声明你的数组是这样的:

" declared as like NSMutableArray *array1;" " 声明为像 NSMutableArray *array1;"

Have you alloc your array before adding objects to it?在向数组添加对象之前,您是否分配了数组?

In other words have you done this?换句话说,你这样做了吗?

NSMutableArray *array1 = [[NSMutableArray alloc] init];

If you only did如果你只做了

NSMutableArray *array1;

That will only declare a pointer to a NSMutableArray object.这只会声明一个指向 NSMutableArray object 的指针。 It doesn't point to an instance of a NSMutableArray object.它不指向 NSMutableArray object 的实例。

When you put [array1 addObject:valueField.text];当你把[array1 addObject:valueField.text]; , you are adding a nil object to your array, just as your error says. ,正如你的错误所说,你正在向你的阵列添加一个 nil object 。 How can valueField.text be equal to something when you just initialized and allocated valueField?刚刚初始化并分配了 valueField,valueField.text 怎么可能等于什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM