在我的iOS应用程序中,我有一个用户界面有两件事:一个选择器视图和一个按钮。添加NSString到NSMutableArray崩溃
我初始化我选择器视图用的NSMutableArray这样的:
@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 ];
}
然后,我有一个按钮,显示弹出,用户可以写的东西。这种方法的目的是为添加一个新的NSString对象到我的NSMutableArray。
- (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的初始化。我在网上搜索了关于它的任何信息,我发现的两个信息是关于初始化,或者它是可变数组而不是简单数组。
此外,我不明白为什么如果我在[self presentViewController:alertController animated:YES completion:nil];
后添加一些代码,它不会被执行......我没有找到任何有关它的信息。
你能帮我弄清楚它为什么崩溃,它不工作? 谢谢
您能否添加您获得的崩溃消息?会让问题变得更容易一点! :) – Rikh
@rikh,是的忘记了。我只是编辑我的帖子;)谢谢! – lilouch
把一个断点放在你试图将'addObject'添加到数组并检查值是否为'nil'? – Rikh