简体   繁体   English

从UITextField向NSMutableArray添加对象

[英]Adding an object to NSMutableArray from UITextField

With this code, I get this error: 有了这段代码,我得到这个错误:

'* -[NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 0' '*-[NSMutableArray insertObject:atIndex:]:尝试在0处插入nil对象

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. 如果您尝试添加一个nil对象,则会在NSArray中引发异常。 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. 同样从代码中,您需要实现UIAlertViewDelegate协议,并尝试将对象添加到那里的数组中。 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. 假设nameField和category是iVars,并且在不再需要它们时需要释放它们。 You should also check which button was pressed in the delegate method. 您还应该检查委托方法中按下了哪个按钮。 HTH Dave HTH戴夫

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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