Snowman
Snowman

Reputation: 32071

Adding an object to NSMutableArray from UITextField

With this code, I get this error:

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

categories=[[NSMutableArray alloc] init ];
UIAlertView* dialog = [[UIAlertView alloc] init];
    [dialog setDelegate:self];
    [dialog setTitle:@"Category name"];
    [dialog setMessage:@" "];
    [dialog addButtonWithTitle:@"Cancel"];
    [dialog addButtonWithTitle:@"OK"];

    nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
    [nameField setBackgroundColor:[UIColor whiteColor]];
    [dialog addSubview:nameField];

    [dialog show];
    [dialog release];

    [categories addObject:[nameField text]];

    [nameField release];
    [categoryTable reloadData];

When I run this in simulator, I get a crash before the alert view even pops up. Any ideas?

Upvotes: 0

Views: 450

Answers (1)

Magic Bullet Dave
Magic Bullet Dave

Reputation: 9076

An exception will be raised in an NSArray if you try to add a nil object. Check for the condition first:

if ([nameField text]) [categories addObject:[nameField text]];

EDIT:

Also from your code, you need to implement the UIAlertViewDelegate protocol and attempt to add your object to your array there. For example:

- (void) showDialog {
    UIAlertView* dialog = [[UIAlertView alloc] init];
    [dialog setDelegate:self];
    [dialog setTitle:@"Category name"];
    [dialog setMessage:@" "];
    [dialog addButtonWithTitle:@"Cancel"];
    [dialog addButtonWithTitle:@"OK"];

    nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
    [nameField setBackgroundColor:[UIColor whiteColor]];
    [dialog addSubview:nameField];

    [dialog show];
    [dialog release];
}


- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {

    if ([nameField text]) [categories addObject:[nameField text]];
    [categoryTable reloadData];

}

Assumes nameField and categories are iVars and you will need to release them when they are no longer needed. You should also check which button was pressed in the delegate method. HTH Dave

Upvotes: 1

Related Questions