Ios NSFileManager createFileAtPath在iPad上失败,但在模拟器上工作
我正在尝试为我的应用程序的每次执行编写一个简单的日志文件。日志文件名基于当前时间并存储在应用程序目录中。下面的代码是我正在尝试的,它可以在模拟器上运行,但当我在iPad上执行时,它会失败,出现“不允许操作”(errno.h中的EPERM) 我也尝试了注释掉的代码,但也失败了。我是iOS编程新手,所以可能缺少一些基本的东西。无论如何,上面的输出表单在iPad上显示了以下内容:Ios NSFileManager createFileAtPath在iPad上失败,但在模拟器上工作,ios,objective-c,nsfilemanager,createfile,Ios,Objective C,Nsfilemanager,Createfile,我正在尝试为我的应用程序的每次执行编写一个简单的日志文件。日志文件名基于当前时间并存储在应用程序目录中。下面的代码是我正在尝试的,它可以在模拟器上运行,但当我在iPad上执行时,它会失败,出现“不允许操作”(errno.h中的EPERM) 我也尝试了注释掉的代码,但也失败了。我是iOS编程新手,所以可能缺少一些基本的东西。无论如何,上面的输出表单在iPad上显示了以下内容: 2013-05-10 14:54:51.794 RichTest1[128:907] Failed to create f
2013-05-10 14:54:51.794 RichTest1[128:907] Failed to create file:
/var/mobile/Applications/XXXX/RichTest1.app/20130510145451.log Operation not permitted
但在模拟器上它可以工作:
2013-05-10 15:07:14.696 RichTest1[1604:c07] Successfully created file:
Users/abruce/Library/Application Support/iPhone Simulator/6.1/Applications/XXXX/RichTest1.app/20130510150714.log
我哪里做错了
--编辑
以下是GetLogFileNameForTimeNow
-(NSString*)GetLogFileNameForTimeNow
{
NSString* FileName = [NSString stringWithFormat:@"%@.log", [self GetTimeAsString] ];
NSString* AppFolderPath = [[NSBundle mainBundle] resourcePath];
return [NSString stringWithFormat:@"%@/%@", AppFolderPath, FileName];
}
-(NSString*)GetTimeAsString
{
return [mDateFormatter stringFromDate:[NSDate date]];
}
在我的类的构造函数中,日期格式化程序的设置如下:
mDateFormatter = [[NSDateFormatter alloc] init];
NSString* DateFormat = @"yyyyMMddHHmmss";
[mDateFormatter setDateFormat:DateFormat];
您正试图在设备上只读的应用程序包内创建文件。将文件放入应用程序的文档或库目录。您试图在没有创建文件权限的位置创建文件, 在“文档”文件夹中创建文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"20130510150714.log"];
BOOL Success = [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
我已通过更改GetLogFileNameForTimeNow函数修复了此问题,如下所示:
-(NSString*)GetLogFileNameForTimeNow
{
NSString* FileName = [NSString stringWithFormat:@"%@.log", [self GetTimeAsString] ];
NSArray* Paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* DocumentsDirectory = [Paths objectAtIndex:0]; // Get documents folder
return [NSString stringWithFormat:@"%@/%@", DocumentsDirectory, FileName];
}
显示
GetLogFileNameForTimeNow
的代码。它已保存到应用程序文件夹中,我将在此处添加该文件夹,但注释中不允许使用代码。现在可以通过将文件夹代码保存到文档中来工作,但是正确的做法是编辑原始问题并添加附加代码作为更新。谢谢,我现在已经更新了原始问题谢谢您的回复。我原以为我有权限写入应用程序包目录,但我想没有!谢谢,我会试试这个。
-(NSString*)GetLogFileNameForTimeNow
{
NSString* FileName = [NSString stringWithFormat:@"%@.log", [self GetTimeAsString] ];
NSArray* Paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* DocumentsDirectory = [Paths objectAtIndex:0]; // Get documents folder
return [NSString stringWithFormat:@"%@/%@", DocumentsDirectory, FileName];
}