在我的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