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

I am creating a custom cell.

In this I added 3 text fields. so I want to save these text field values ​​in nsmutablearray.

when i try to use 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 get an 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.

+4
source share
5 answers
 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 code above will work just fine for you.

+2
source

Just add this condition to check if the text field is empty (i.e. textfield.text = nil):

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

This will check if the text field is empty, it will add a blank line. If you don't want this to just skip the else part.

+2
source

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

+2
source

I noticed that you said you declared your array as follows:

"declared as NSMutableArray * array1;"

Do you add your array before adding objects to it?

In other words, did you do it?
 NSMutableArray *array1 = [[NSMutableArray alloc] init]; 

If you just did

 NSMutableArray *array1; 

This will only declare a pointer to an NSMutableArray object. It does not point to an instance of an NSMutableArray object.

+1
source

When you put [array1 addObject:valueField.text]; , you add the null object to your array, just like your error says. How can valueField.text be equal when you just initialized and assigned valueField?

0
source

All Articles