从的UITextField
问题描述:
将对象添加到NSMutableArray里有了这个代码,我得到这个错误:从的UITextField
'* -[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];
当我在模拟器中运行这个,我得到一个崩溃前的警报视图甚至弹出。有任何想法吗?
答
如果您尝试添加零对象,则会在NSArray中引发异常。检查条件第一:
if ([nameField text]) [categories addObject:[nameField text]];
编辑:
从您的代码此外,您还需要实现UIAlertViewDelegate协议,并尝试将对象添加到您的阵中还有。例如:
- (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是iVars,您将需要在不再需要时释放它们。您还应该检查委托方法中按下了哪个按钮。 HTH戴夫
嗯好吧,这似乎已经解决了这个问题,但是当我插入时我的表中没有显示出来。使用此代码:'if([nameField text])[类别insertObject:[nameField text] atIndex:[categories count]];',我的表中没有任何内容出现。但是,如果我使用'[类别insertObject:@“test”atIndex:[categories count]];',那么“test”确实出现在我的表中。什么可能导致这种情况? – Snowman
您需要创建您的UIAlertView,然后显示它,而不是其他任何东西。方法中的其余代码将继续运行[dialog show]调用(即,无对象被传递给数组)。一旦你触摸了一个按钮,相应的委托方法就会被调用。在那里你应该尝试做一些结果。 –
我该怎么做? – Snowman