我正在尝试为我的应用程序的每次执行编写一个简单的日志文件。日志文件名基于当前时间,存储在 app 目录中。下面的代码是我正在尝试在模拟器上运行的代码,但是当我在 iPad 上执行时,它会因“不允许操作”而失败(errno.h 中的 EPERM)。
-(BOOL)CreateLogFile
{
mLogFilePath = [self GetLogFileNameForTimeNow];
BOOL Success = [[NSFileManager defaultManager] createFileAtPath:mLogFilePath contents:nil attributes:nil];
/*BOOL Success = [[NSFileManager defaultManager] createFileAtPath:mLogFilePath contents:nil attributes:[NSDictionary dictionaryWithObject:NSFileProtectionComplete
forKey:NSFileProtectionKey]];*/
if ( Success )
{
NSLog( @"Successfully created file: %@", mLogFilePath );
mLogFileHandle = [NSFileHandle fileHandleForWritingAtPath:mLogFilePath];
[self WriteInstanceInformationToLog];
}
else
{
NSLog( @"Failed to create file: %@ %s", mLogFilePath, strerror(errno) );
}
return Success;
}
我也尝试了注释掉的代码,但这也失败了。我是 iOS 编程新手,所以可能缺少一些基本的东西。无论如何,上面的输出形式在 iPad 上显示以下内容:
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
我哪里错了?
--edit 这里是代码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];