我正在尝试在我的应用程序库目录中的子目录中创建文件。首先,我得到这样的图书馆路径:
- (NSURL*) getLibraryDirectory
{
NSFileManager* manager = [NSFileManager defaultManager];
NSArray* paths = [manager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask];
if ([paths count] > 0)
{
return [paths objectAtIndex:0];
}
return nil;
}
然后我使用以下代码创建子文件夹:
- (NSURL*) getDirectory:(NSString*)subdirName
{
NSFileManager* sharedFM = [NSFileManager defaultManager];
NSURL* libraryDirectory = [self getLibraryDirectory];
if (libraryDirectory)
{
NSURL* subdir = [libraryDirectory URLByAppendingPathComponent:subdirName isDirectory:YES];
if (![sharedFM fileExistsAtPath:[subdir absoluteString] isDirectory:YES])
{
NSError* error;
if ([sharedFM createDirectoryAtURL:subdir withIntermediateDirectories:YES attributes:nil error:&error])
{
return subdir;
}
else
{
NSLog(@"Error occured while trying to create subdirectory \"%@\". Code - %d, desc - %@", subdirName, [error code], [error localizedDescription]);
}
}
}
return nil;
}
最后一件事我试图在这个文件夹中创建一些文件,如下所示:
NSString* filePath = [[self getDirectory:DIR_COMMANDS] absoluteString];
if (filePath)
{
filePath = [filePath stringByAppendingPathComponent:@"test_file.tst"];
NSFileManager* manager = [NSFileManager defaultManager];
if ([manager createFileAtPath:filePath contents:[[NSData alloc] initWithBytes:[[@"string" dataUsingEncoding:NSUTF16LittleEndianStringEncoding] bytes] length:12] attributes:nil])
{
NSLog(@"YES");
}
else
{
NSLog(@"NO");
}
}
但不幸的是,我每次都得到“不”,不明白为什么。