使用此代码,我收到此错误:
'* -[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];
当我在模拟器中运行它时,在弹出警报 View 之前我就崩溃了。有什么想法吗?
最佳答案
如果你尝试添加一个 nil 对象,NSArray 中将会引发异常。首先检查情况:
if ([nameField text]) [categories addObject:[nameField text]];
编辑:
此外,从您的代码中,您需要实现 UIAlertViewDelegate 协议(protocol)并尝试将对象添加到那里的数组中。例如:
- (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];
}
假设 nameField 和categories 是 iVar,当不再需要它们时,您需要释放它们。您还应该检查委托(delegate)方法中按下了哪个按钮。 HTH 戴夫
关于iphone - 从 UITextField 添加一个对象到 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7109433/