在可可中解压缩文件

boo*_*oom 7 cocoa

我有一个压缩文件,我想提取它的内容.我应该做些什么来实现它.是否有任何框架可以在cocoa框架或目标C中解压缩文件.

Sam*_*fes 6

如果您在iOS上或不想使用NSTask或其他什么,我推荐我的图书馆SSZipArchive.

用法:

NSString *path = @"path_to_your_zip_file";
NSString *destination = @"path_to_the_folder_where_you_want_it_unzipped";
[SSZipArchive unzipFileAtPath:path toDestination:destination];
Run Code Online (Sandbox Code Playgroud)

很简单.


cod*_*nd1 6

在Mac上,您可以使用内置unzip命令行工具NSTask:

- (void) unzip {
    NSFileManager* fm = [NSFileManager defaultManager];
    NSString* zipPath = @"myFile.zip";

    NSString* targetFolder = @"/tmp/unzipped"; //this it the parent folder
                                               //where your zip's content 
                                               //goes to (must exist)

    //create a new empty folder (unzipping will fail if any
    //of the payload files already exist at the target location)
    [fm createDirectoryAtPath:targetFolder withIntermediateDirectories:NO 
                                           attributes:nil error:NULL];


    //now create a unzip-task
    NSArray *arguments = [NSArray arrayWithObject:zipPath];
    NSTask *unzipTask = [[NSTask alloc] init];
    [unzipTask setLaunchPath:@"/usr/bin/unzip"];
    [unzipTask setCurrentDirectoryPath:targetFolder];
    [unzipTask setArguments:arguments];
    [unzipTask launch];
    [unzipTask waitUntilExit]; //remove this to start the task concurrently

}
Run Code Online (Sandbox Code Playgroud)

这是一个快速而肮脏的解决方案.在现实生活中,您可能希望进行更多的错误检查,并查看有关花哨参数的unzip 联机帮助页.


Col*_*ett 3

如果您只想解压缩文件,我建议使用NSTask调用 unzip(1)。在解压缩之前,将文件复制到您控制的目录(可能在 /tmp 中)可能是明智的做法。

  • 你无法控制/tmp,任何人都可以写入它。 (5认同)
  • 使用`NSTemporaryDirectory()`而不是`/tmp`,尽管要小心,它的行为有点像`/var/tmp`。它会被清除,但并不总是在重新启动时。 (4认同)