Thukaram
Thukaram

Reputation: 1083

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

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.

Upvotes: 4

Views: 3974

Answers (5)

Zhang
Zhang

Reputation: 11607

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.

Upvotes: 1

Bushra Shahid
Bushra Shahid

Reputation: 3579

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.

Upvotes: 2

Raj
Raj

Reputation: 6015

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.

Upvotes: 2

Dylan Reich
Dylan Reich

Reputation: 1430

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?

Upvotes: 0

Perception
Perception

Reputation: 80603

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.

Upvotes: 2

Related Questions