在我的 iOS 应用程序中,我有一个包含两部分的用户界面:一个选择器 View 和一个按钮。
我用这样的 NSMutableArray 初始化我的选择器 View :
@interface ViewController ()
{
NSMutableArray *_pickerDataCategory;
}
- (void)viewDidLoad
{
// Initialize Data
_pickerDataCategory = [[NSMutableArray alloc] init];
NSMutableArray *array = [NSMutableArray arrayWithObjects:
@"cat1", @"cat2", @"cat3", @"cat4", nil ];
_pickerDataCategory = array;
//First I had initialize like this : NSMutableArray *_pickerDataCategory = [NSMutableArray arrayWithObjects:
@"cat1", @"cat2", @"cat3", @"cat4", nil ];
}
然后我有一个按钮,它显示一个弹出窗口,用户可以在其中写东西。此方法的目的是向我的 NSMutableArray 添加一个新的 NSString 对象。
- (IBAction)addNewCategory:(id)sender {
__block bool isNotExist = false;
UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"Add new category"
message: @"Please write a new category"
preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"Category";
textField.textColor = [UIColor blueColor];
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.borderStyle = UITextBorderStyleRoundedRect;
}];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[alertController dismissViewControllerAnimated:YES completion:nil];
}];
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSString *input = alertController.textFields[0].text;
//Check if the category exist already
for (NSString *category in _pickerDataCategory)
{
if ([category isEqualToString:input])
{
[self popupMessage:@"Category already exists" title:@"Error"];
isNotExist = false;
return;
}else{
NSString *msg = [@"Category has been added : " stringByAppendingString:input];
[self popupMessage:msg title:@"Ok"];
isNotExist = true;
//[_pickerDataCategory addObject:input];//CRASH
// [_picker_cateogry reloadAllComponents];
}
}
}];
[alertController addAction:cancel];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
}
但是当我想将文本字段输入添加到我的 NSMutableArray 时它崩溃了。我真的不明白为什么。我对我的 NSMutableArray 的初始化很小心。我在 Internet 上查找了有关它的任何信息,我发现的两个信息要么是关于初始化的,要么是关于它是可变数组而不是简单数组的。
此外,我不明白为什么如果我在 [self presentViewController:alertController animated:YES completion:nil];
之后添加一些代码,它不会被执行...我没有找到任何以及有关它的信息。
你能帮我弄清楚为什么它崩溃了,它不工作吗? 谢谢
最佳答案
就您的崩溃而言,这可能与您在枚举数组时试图修改它有关。我会将这些分解为两个独立的任务。
有点像...
NSMutableArray *additionalObjects = [[NSMutableArray alloc] init];
for (NSString *category in _pickerDataCategory) {
if (![category isEqualToString:input]) {
[additionalObjects addObject: category];
}
}
[_pickerDataCategory addObjectsFromArray: additionalObjects];
关于ios - 将 NSString 添加到 NSMutableArray 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41021351/