iphone - 从 UITextField 添加一个对象到 NSMutableArray

标签 iphone objective-c ios cocoa-touch uialertview

使用此代码,我收到此错误:

'* -[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/

相关文章:

iphone - 使用动画删除 UITableView Cell

ios - 如何调整 UIScrollView 的大小以适应子 UITextViews 的内容

iphone - 有没有办法在一段时间后自动关闭警报 View ?

ios - 如果属性名为 swipeDirection,为什么 self.SwipeDirection 可以工作?

iOS 4.3 : How to handle the logging message: "Received memory warning. Level=1"?

ios autolayout 不会更改按钮框架位置

iphone - 任何基于 Windows 的 IDE 来查看 objective-c 代码?

iphone - Linkedin API 要求提供成员(member) ID

iphone - iOS 中使用 Storyboard View 或单独的 Nib 的自定义弹出窗口

php - 使用 Charles 和 SSL Apple 推送地址