Objective c: How to only delete all file under a directory but keep the directory itself

后端 未结 2 391
礼貌的吻别
礼貌的吻别 2021-02-04 13:54

I found the code below to delete file in objective-c, but I want to only delete all files under directory of Caches and keep the directory Caches itsel

相关标签:
2条回答
  • 2021-02-04 14:12

    Loop through the files in that directory.

    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSArray *fileArray = [fileMgr contentsOfDirectoryAtPath:directory error:nil];
    for (NSString *filename in fileArray)  {
    
        [fileMgr removeItemAtPath:[directory stringByAppendingPathComponent:filename] error:NULL];
    }
    
    0 讨论(0)
  • 2021-02-04 14:14
    - (void) removeDocuments
    {
        NSString *docDir = // get documents directory
        NSString *cacheDir = [docDir stringByAppendingPathComponent: @"cacheDir"];
    
        // check if cache dir exists
    
        // get all files in this directory
        NSFileManager *fm = [NSFileManager defaultManager];
        NSArray *fileList = [fm contentsOfDirectoryAtPath: cacheDir error: nil];
    
        // remove
        for(NSInteger i = 0; i < [fileList count]; ++i)
        {
            NSString *fp =  [fileList objectAtIndex: i];
            NSString *remPath = [cacheDir stringByAppendingPathComponent: fp];
            [fm removeItemAtPath: remPath error: nil];
        }
    }
    
    0 讨论(0)
提交回复
热议问题