开发者

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

开发者 https://www.devze.com 2023-03-27 14:10 出处:网络
i am creating custom cell. In that i added 3 textfields. so i want to store that textfield values into nsmutablearray.

i am creating custom cell.

In that i added 3 textfields. so i want to store that textfield values into 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.


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.


The text attribute of UITextField is nil by default. Set it to an empty string before adding it to your array, though I think this is not what you are trying to achieve.


Just add this condition to check if the textfield is empty (i.e. 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.


I noticed you said you declared your array like so:

" declared as like 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. It doesn't point to an instance of a NSMutableArray object.


When you put [array1 addObject:valueField.text];, you are adding a nil object to your array, just as your error says. How can valueField.text be equal to something when you just initialized and allocated valueField?

0

精彩评论

暂无评论...
验证码 换一张
取 消