2013-11-23 4 views
0

я получаю эти ошибки, когда я пытаюсь использовать удалить с кодом я разместил ниже:Как удалить из uitableview с plist?

 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (6) must be equal to the number of rows contained in that section before the update (6), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).' 

я пытаюсь использовать удалить, когда я нажимаю на кнопку редактирования. он показывает, что я могу удалить, когда я попытаюсь показать вышеприведенную ошибку.

MainViewController.m

- (void)viewWillAppear:(BOOL)animated{ 
// Property List.plist code 
//Gets paths from root direcory. 
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
//Get documents path. 
NSString *documentsPath = [paths objectAtIndex:0]; 

//Get the path to our PList file. 
plistPath = [documentsPath stringByAppendingPathComponent:@"Servers.plist"]; 

//Check to see if Property List.plist exists in documents. 
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]){ 
    [[NSFileManager defaultManager]copyItemAtPath:[[NSBundle mainBundle]pathForResource:@"Servers" ofType:@"plist"] toPath:plistPath error:nil]; 
    //If not in documents, get property list from main bundle. 
} 
arrayA = [[NSMutableArray alloc] initWithContentsOfFile:plistPath]; 
NSLog(@"%@\n%@", arrayA, [arrayA valueForKey:@"Hostname"]); 

tableData = [arrayA valueForKey:@"Hostname"]; 
[super viewWillAppear:animated]; 
[self.mainTableView reloadData]; 

}

- (IBAction)setEditMode:(UIBarButtonItem *)sender { 

if 
    (self.editing) 
{ 
    sender.title = @"Edit"; 
    sender.style = UIBarButtonItemStylePlain; 
    [self.mainTableView setEditing:NO animated:YES]; 
    [super setEditing:NO animated:YES]; 

} 
else 
{ 
    sender.title = @"Done"; 
    sender.style = UIBarButtonItemStyleDone; 
    [super setEditing:YES animated:YES]; 
    [self.mainTableView setEditing:YES animated:YES]; 
} 

}

- (NSInteger)tableView:(UITableView *)mainTableView numberOfRowsInSection:(NSInteger)section 
{ 

return [tableData count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

{

static NSString *cellIdentifier = @"showServerAction"; 

UITableViewCell *cell = [mainTableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

if (cell == nil) { 

    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 

} 

cell.textLabel.text = [tableData objectAtIndex:indexPath.row]; 

return cell; 

}

- (void)tableView:(UITableView *)mainTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ 
//- (void)tableView:(UITableView *)mainTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 

if (editingStyle == UITableViewCellEditingStyleDelete) { 
    [arrayA writeToFile:plistPath atomically: TRUE]; 
    [self.mainTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    [self.mainTableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade]; 

} 
} 
+2

Это похоже на точный дубликат вашего предыдущего вопроса (для которого у вас есть ответ, который хорошо выглядит для меня). –

+0

Возможно, это дубликат. Однако. Я получаю сообщение об ошибке, когда я пытаюсь использовать один из приведенных кодов кода – KennyVB

+0

Но удаление строки из массива источников данных * является правильным ответом. Если это не сработает для вас, тогда задайте вопрос, который фокусируется на этой проблеме. - (Моя ставка заключается в том, что ваш массив не изменен * и поэтому вы не можете удалить объект.) –

ответ

1

Похоже, ваши данные хранятся в tableData и при вызове deleteRowsAtIndexPaths, вы не вынимая соответствующие данные из tableData. Если вы должны были вызвать reloadData в этой таблице, данные фактически не исчезнут, потому что вы не удалили их из источника данных. Я также согласен с Martin R в том, что данные, которые вы получаете из массива, вероятно, не изменяемы. Чтобы создать изменяемый источник данных вы могли бы сделать что-то вроде:

tableData = [[arrayA valueForKey:@"Hostname"] mutableCopy]; 

(Убедитесь, что tableData объявлен NSMutableArray)

Тогда, когда вы получаете commitEditingStyle, удалить данные из tableData что-то вроде:

[tableData removeObjectAtIndex:indexPath.row]; 

Если вы разрешаете удалять несколько строк, вам придется разрешить это, возможно, используя removeObjectsInRange.

+0

, который работал на самом деле. теперь мне просто нужно найти способ для этого написать plist. потому что сейчас, когда я перезагружаю приложение. удаленный загружается снова, как если бы он не писал plist – KennyVB

Смежные вопросы