2013-02-15 2 views
2

У меня есть UITableView, который заполняется по ключам массива из списка свойств с помощью этого кода:Как удалить массив из plist с помощью commitEditingStyle?

-(void)viewWillAppear:(BOOL)animated 
{ 
    // get paths from root direcory 
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
    // get documents path 
    NSString *documentsPath = [paths objectAtIndex:0]; 
    // get the path to our Data/plist file 
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"]; 
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:(NSString *)plistPath]; 
    viewerKeys = [dictionary allKeys]; 

    [self.tableView reloadData]; 
} 

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

     UILabel *label = (UILabel *)[cell viewWithTag:1000]; 
     label.text = [viewerKeys objectAtIndex:indexPath.row]; 
     return cell; 
} 

Я пытаюсь включить салфетки, чтобы удалить в каждой строке в виде таблицы, и, конечно, это означает, Мне нужно удалить строку, а также массив в plist. Это то, что я пытался до сих пор:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
    // get documents path 
    NSString *documentsPath = [paths objectAtIndex:0]; 
    // get the path to our Data/plist file 
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"]; 
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:(NSString *)plistPath]; 

    NSString *key = [viewerKeys objectAtIndex:indexPath.row]; 
    [dictionary removeObjectForKey:[NSString stringWithFormat:@"%@", key]]; 


    NSArray *indexPaths = [NSArray arrayWithObject:indexPath]; 
    [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic]; 
} 

Однако он не записывает данные обратно в PLIST, и я получаю эту ошибку:

Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (2), 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).

Это то, что мой внешний вид Plist например:

<plist version="1.0"> 
<dict> 
    <key>(null)</key> 
    <array> 
     <string>Username</string> 
     <string>Password</string> 
     <string>http://www.google.com</string> 
     <string>/whatever</string> 
    </array> 
    <key>Hello</key> 
    <array> 
     <string>admin</string> 
     <string></string> 
     <string>https://www.whatever.com</string> 
     <string>/things</string> 
    </array> 
</dict> 
</plist> 

Любая помощь будет замечательной!

+0

Вы не обновляя PLIST после удаления. Напишите словарь обратно в файл –

ответ

1

Ваша проблема в том, что вы удаляете этот объект только из словаря. ваш viewerKeys все еще удерживает удаленные объекты. Вам необходимо обновить viewerKeys перед вызовом deleteRowsAtIndexPaths:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
// get documents path 
NSString *documentsPath = [paths objectAtIndex:0]; 
// get the path to our Data/plist file 
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"]; 
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:(NSString *)plistPath]; 

NSString *key = [viewerKeys objectAtIndex:indexPath.row]; 
[dictionary removeObjectForKey:[NSString stringWithFormat:@"%@", key]]; 


[dictionary writeToFile:plistPath atomically:YES]; 
viewerKeys = [dictionary allKeys]; 

NSArray *indexPaths = [NSArray arrayWithObject:indexPath]; 
[tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic]; 

}

+0

Это сработало - большое вам спасибо! –

+0

@ChrisByatt Операции с файлами стоят дорого. Чтение и запись каждый раз из файла не очень хорошо. Вы можете подумать об альтернативе. Поддерживайте кеш в вашем словаре словаря для хранения сведений. Чтение/запись только один раз в файл. В других случаях используйте этот словарь. Для совместного использования вы можете использовать Singleton class –

+0

Я знаю, что это не идеально, однако эти операции редко случаются, так как идея приложения настроена один раз, а не снова. –

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