如何删除文档目录中的特定项目 ios objective c

how to delete the specific item in the document directory ios objective c

我想从 DocumentDirectory 中删除特定项目,即我在 DocumentDirectory 中有 50 个对象,我想从中删除 5 个不同的元素。我使用以下代码获取 DocumentDirectory 对象。

NSURL *vedioURL;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:nil];

NSLog(@"files array %@", filePathsArray);

谁能帮我解决这个问题

你可以这样试试

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (filePathsArray.count >= 6) {
    for (NSInteger i=filePathsArray.count-6; i < filePathsArray.count; i++) {
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[filePathsArray objectAtIndex:i]];
        if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])  {
           NSError *error;
            if (![[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]) {
                NSLog(@"Delete error: %@", error);
            }
        }
    }
}

您可以尝试以下方法

NSString *path = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [paths[0] stringByAppendingPathComponent:@"YOUR DIR"];
path = [path stringByAppendingPathComponent:@"YOUR FILE"];
NSError *error;
if ([[NSFileManager defaultManager] fileExistsAtPath:path])     
{
    if (![[NSFileManager defaultManager] removeItemAtPath:path error:&error])   //Delete it
    {
        NSLog(@"Delete file error: %@", error);
    }
}