gpt4 book ai didi

objective-c - 使用 NSApplicationSupportDirectory 创建新目录时附加 NSString

转载 作者:行者123 更新时间:2023-12-03 16:55:42 31 4
gpt4 key购买 nike

我在使用 NSApplicationSupportDirectory 时一直尝试在应用程序支持文件夹内创建一个新文件;我可以向其中写入文件,但无法在应用程序支持中创建文件夹。

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;

最佳答案

也许 solution Cocoa with Love 上提供的可能有用吗?

摘录:

- (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;
}

关于objective-c - 使用 NSApplicationSupportDirectory 创建新目录时附加 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4975968/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com