gpt4 book ai didi

ios - 当 iOS 中的 NSMutableArray 没有对象时应用程序崩溃

转载 作者:行者123 更新时间:2023-11-28 19:03:57 25 4
gpt4 key购买 nike

我有四个文本字段,如 textfield1textfield2textfield3textfield4 和一个按钮。当我单击按钮时,我将文本字段文本添加到 NSMutableArray 并填充到 tableview 中。

我的代码是:

- (void)buttonClick
{
NSMutableArray *array =[[NSMutableArray alloc]init];
[array addObject: textfield1.text];
[array addObject: textfield2.text];
[array addObject: textfield3.text];
[array addObject: textfield4.text];
}

使用委托(delegate)方法在 TableView 中填充

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}

cell.textLabel.text =[array objectAtIndex:indexPath.row];
return cell;
}

上面的代码运行良好。但是,当我在没有在文本字段中输入任何数据的情况下单击按钮时,应用程序崩溃了,因为数组是空的。如何解决这个问题?

最佳答案

您不能将 nil 添加到数组。

[array addObject:textfield1.text ?: @""];
[array addObject:textfield2.text ?: @""];
[array addObject:textfield3.text ?: @""];
[array addObject:textfield4.text ?: @""];

这确保数组中有四个项目(可能是空字符串)。

关于ios - 当 iOS 中的 NSMutableArray 没有对象时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22195470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com