删除指定目录下的所有文件后无法清理内存

Vat*_*kla 2 xcode objective-c nsfilemanager ios nshomedirectory


在我的项目中介绍,我要删除文件夹及其内容,所以我尝试了这个接受的答案ClickHere

它工作,我认为任务结束但删除整个文件夹(目录)后,我看到内存仍然分配但文件不存在.
这是我删除目录(文件夹)的代码.

-(BOOL)removeItem:(NSString*)name{
    //name: is directory(folder)'s name
    NSString*path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    path = [path stringByAppendingPathComponent:@"Normal"];
    path = [path stringByAppendingPathComponent:name];
    NSError* err;
    NSArray* list = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:path error:&err];
    if(err){
        NSLog(@"\n##CONTENTS OF DIRECTORY ERROR:->\n%@",err.localizedDescription);
    }
    //if array's count is not zero(0) it means directory has files available.
    if(list.count >= 1){
        for(NSString* string in list){
            [[NSFileManager defaultManager]removeItemAtPath:[path stringByAppendingPathComponent:string] error:&err];
            if(err){
                NSLog(@"\n##FOLDER IN FOLDER ERROR:->\n%@",err.localizedDescription);
            }
        }
        [[NSFileManager defaultManager]removeItemAtPath:path error:&err];
        return YES;
    }else{
        [[NSFileManager defaultManager]removeItemAtPath:path error:&err];
        if (err) {
            return NO;
        }
        return YES;
    }
}
Run Code Online (Sandbox Code Playgroud)


提前致谢.

Vat*_*kla 7

好吧,我得到了问题.在我的情况下,问题是一个临时文件夹(目录).当我将视频添加到我的应用程序时,iOS在应用程序的临时文件夹(目录)中创建了一些临时文件.所以,从我的应用程序中删除文件(视频)后,我在设置 - >常规 - >使用 - >管理存储中看到的应用程序的大小是临时文件夹的大小.
因此,当您从Gallery导入照片或视频时,您必须在获取后手动清除临时文件夹.我正在从UIImagePickerController的委托中清除临时文件夹,如下所示.

-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info{
[self dismissViewControllerAnimated:YES completion:^{
BOOL success = [videoData writeToFile:path atomically:YES];
            NSLog(@"Successs:::: %@", success ? @"YES" : @"NO");
            [RWTAppDelegate clearTmpDirectory];
}];
}
Run Code Online (Sandbox Code Playgroud)


+ (void)clearTmpDirectory
{
    NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
    for (NSString *file in tmpDirectory) {
        [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
    }
}
Run Code Online (Sandbox Code Playgroud)


更新swift 3+

class func clearTmpDirectory(){
        let path = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
        let manager = FileManager.default
        let files = try? manager.contentsOfDirectory(atPath: path.path)
        files?.forEach { (file) in
            let temp = path.appendingPathComponent(file)
            try? manager.removeItem(at: temp)
            // --- you can use do{} catch{} for error handling ---//
        }
}
Run Code Online (Sandbox Code Playgroud)


对不起,我的英语不好.