简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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