【问题标题】:Adding an object to NSMutableArray from UITextField从 UITextField 向 NSMutableArray 添加一个对象
【发布时间】:2011-08-18 14:51:30
【问题描述】:

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

'* -[NSMutableArray insertObject:atIndex:]: 尝试插入 nil 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];

当我在模拟器中运行它时,我什至在警报视图弹出之前就崩溃了。有什么想法吗?

【问题讨论】:

    标签: iphone objective-c ios cocoa-touch uialertview


    【解决方案1】:

    如果您尝试添加一个 nil 对象,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 是 iVar,您需要在不再需要它们时释放它们。您还应该检查在委托方法中按下了哪个按钮。 HTH 戴夫

    【讨论】:

    • 嗯好吧,这似乎已经解决了这个问题,但是当我插入时,我的表中没有显示任何内容。使用此代码:if ([nameField text]) [categories insertObject:[nameField text] atIndex:[categories count]];,我的表中没有任何内容。但是,如果我使用[categories insertObject:@"test" atIndex:[categories count]];,那么“测试”确实会出现在我的表格中。是什么原因造成的?
    • 您需要创建您的 UIAlertView 然后显示它,仅此而已。您方法中的其余代码将继续运行通过 [dialog show] 调用(即,将 nil 对象传递给数组)。一旦你触摸一个按钮,相应的委托方法就会被调用。在那里你应该尝试对结果做点什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多