使用NSTemporaryDirectory创建临时文件时出错

时间:2015-11-01 14:42:35

标签: ios objective-c

在IOS 9.1中,以下代码显然存在问题。我做错了什么?

NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"foobar.dat"];
NSString *s = @"testing";
NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
BOOL ok = [data writeToFile:filePath options:NSDataWritingAtomic error:&error];
if(!ok) {
    NSLog(@"=== error writing to path %@, %@", filePath, error.debugDescription);
}

日志说

=== error writing to path /var/folders/gf/4429772177s9rr234wzlwpz00000gp/T/foobar.dat, 
Error Domain=NSCocoaErrorDomain Code=4 "The folder “foobar.dat” doesn’t exist." 
UserInfo={NSURL=file:///var/folders/gf/4429772177s9rr234wzlwpz00000gp/T/foobar.dat, 
NSUnderlyingError=0x15e0bc20 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}, NSUserStringVariant=Folder}

这只发生在我的iPhone上,而不是模拟器中。手机中有可用空间GB。谢谢你的帮助。

修改 添加了代码以检查临时目录是否存在,如果不存在,则创建它:

NSString *dirPath = NSTemporaryDirectory();
NSFileManager *fm = [NSFileManager defaultManager];
BOOL isDir = NO;
NSError *error = nil;
if (! [fm fileExistsAtPath:dirPath isDirectory:&isDir]) {
    NSLog(@"Directory does not exist at dirPath %@", dirPath);
    BOOL success = [fm createDirectoryAtPath:dirPath
                 withIntermediateDirectories:YES attributes:nil error:&error];
    if (!success) {
        NSLog(@"=== error: %@", error.debugDescription);
    }
}

同样,此错误仅发生在我的测试iPhone 5C上,而不是模拟器上。 记录

Directory does not exist at dirPath /var/folders/gf/4429772177s9rr234wzlwpz00000gp/T/
=== error: Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “T” in the folder “4429772177s9rr234wzlwpz00000gp”." 
    UserInfo={NSFilePath=/var/folders/gf/4429772177s9rr234wzlwpz00000gp/T/, NSUnderlyingError=0x1765cdf0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

如错误所示,如果最后一个路径组件(' T')被视为文件名,则错误(513 =错误权限)是有意义的。因此,创建文件夹的问题与编写文件的问题类似,即最后一个路径组件被误解。我还检查了尾随' /'在dirPath字符串中是最后一个字符,它是。

0 个答案:

没有答案
相关问题