我一直在尝试使用NSApplicationSupportDirectory在我的应用程序支持文件夹中创建一个新文件;我可以写一个文件,但我无法在Application Support中创建一个文件夹。
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the application support: (attempting to create the blasted directory inside of application support directory
NSString *fileName = [NSString stringWithFormat:@"%@/managersemail.txt",
applicationDirectory];
//create content - formats with the managersemail.txt location
NSString* content = [NSString stringWithFormat:@"%@",[nameField stringValue]];
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
NSDictionary* errorDict;
我上面列出的代码效果很好,除了有关创建我想放置managersemail.txt的文件夹的部分。我试图模仿NSString *内容中列出的stringWithFormat,然后改变几种方式但无济于事!有什么想法吗?
NSAppleEventDescriptor* returnDescriptor = NULL;
答案 0 :(得分:3)
也许Cocoa with Love上提供的solution可能有用吗?
摘录:
- (NSString *)findOrCreateDirectory:(NSSearchPathDirectory)searchPathDirectory
inDomain:(NSSearchPathDomainMask)domainMask
appendPathComponent:(NSString *)appendComponent
error:(NSError **)errorOut
{
// Search for the path
NSArray* paths = NSSearchPathForDirectoriesInDomains(
searchPathDirectory,
domainMask,
YES);
if ([paths count] == 0)
{
// *** creation and return of error object omitted for space
return nil;
}
// Normally only need the first path
NSString *resolvedPath = [paths objectAtIndex:0];
if (appendComponent)
{
resolvedPath = [resolvedPath
stringByAppendingPathComponent:appendComponent];
}
// Check if the path exists
BOOL exists;
BOOL isDirectory;
exists = [self
fileExistsAtPath:resolvedPath
isDirectory:&isDirectory];
if (!exists || !isDirectory)
{
if (exists)
{
// *** creation and return of error object omitted for space
return nil;
}
// Create the path if it doesn't exist
NSError *error;
BOOL success = [self
createDirectoryAtPath:resolvedPath
withIntermediateDirectories:YES
attributes:nil
error:&error];
if (!success)
{
if (errorOut)
{
*errorOut = error;
}
return nil;
}
}
if (errorOut)
{
*errorOut = nil;
}
return resolvedPath;
}
答案 1 :(得分:1)
也许您可以尝试使用NSFileManager创建文件夹,然后将文件写入文件夹。
NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *applicationSupport = [[NSString stringWithString:@"~/Library/Application Support/'YOUR APP'] stringByExpandingTildeInPath]; if ([fileManager fileExistsAtPath:applicationSupport] == NO) [fileManager createDirectoryAtPath:applicationSupport withIntermediateDirectories:YES attributes:nil error:nil]; NSString *fileName = [NSString stringWithFormat:@"%@/managersemail.txt", applicationSupport]; NSString* content = [NSString stringWithFormat:@"%@",[nameField stringValue]]; //save content to the documents directory [content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
所以这样的事情应该有效。随意发表评论以提问。