2012-01-21 34 views
0

我想從蘋果的示例代碼DirectoryWatcher和DITableViewController填充的表視圖中刪除一個文件。這是我的代碼,我似乎刪除整個數組而不是單個文件。刪除路徑,而不是整個陣列

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 
    // If row is deleted, remove it from the list. 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     NSInteger row = [indexPath row]; 
     [documentURLs removeObjectAtIndex:row];  
    } 

    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] 
        withRowAnimation:UITableViewRowAnimationFade]; 


    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *pathToDocumentsDirectory = [paths objectAtIndex:0]; 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    BOOL fileExists = [fileManager fileExistsAtPath:pathToDocumentsDirectory]; 
    NSLog(@"Path to file: %@", pathToDocumentsDirectory);   
    NSLog(@"File exists: %d", fileExists); 
    NSLog(@"Is deletable file at path: %d", [fileManager isDeletableFileAtPath:pathToDocumentsDirectory]); 
    if (fileExists) 
    { 
     BOOL success = [fileManager removeItemAtPath:pathToDocumentsDirectory 
               error:&error]; 
     if (!success) 
      NSLog(@"Error: %@", [error localizedDescription]); 
    } 
} 

有人可以幫我弄清楚如何從數組中刪除單個文件嗎?

謝謝!

回答

0

您的代碼嘗試刪除應用程序的Documents目錄。

您需要將URL從documentURLs陣列中取出並傳遞給-[NSFileManager removeItemAtPath:]。例如:

NSURL *urlToDelete = nil; 
if (editingStyle == UITableViewCellEditingStyleDelete) { 
    NSInteger row = [indexPath row]; 
    urlToDelete = [documentURLs objectAtIndex:row]; 
    [documentURLs removeObjectAtIndex:row];  
} 

... 
if (urlToDelete) { 
    BOOL success = [fileManager removeItemAtPath:urlToDelete error:&error); 
    ... 
+0

感謝您的回覆速度快,但搶我得到一個警告,這是不兼容的指針類型發送到NSURL類型的NSString和文件的參數保持 – Dan

+0

'NSFileManager'也有一個叫'方法removeItemAtURL:錯誤:'。 –

+0

這是伎倆羅布,真棒幫助,謝謝! – Dan

相關問題