gpt4 book ai didi

cocoa - 基于 Cocoa 文档的应用程序中文档的默认保存位置

转载 作者:行者123 更新时间:2023-12-03 16:19:01 24 4
gpt4 key购买 nike

我创建了一个基于 Cocoa 文档的绘图应用程序。我希望在“保存/另存为”对话框中使用我的应用程序创建的新文档的默认位置应位于 ~/Pictures/MyAppName/目录中。

我怎样才能实现这个目标?

我或多或少尝试了 Ole 下面的建议,但它不起作用。这是我的prepareSavePanel 的实现。我做错了什么?

- (BOOL)prepareSavePanel:(NSSavePanel *)savePanel
{
if ([self fileURL] == nil) {
//new, not saved yet
[savePanel setExtensionHidden:NO];

//set default save location
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSPicturesDirectory, NSUserDomainMask, YES);

if ([paths count] > 0) {
NSString *userPicturesPath = [paths objectAtIndex:0];
NSString *myDirPath = [userPicturesPath stringByAppendingPathComponent:@"MyAppName"];


//create directory is it doesn't already exist
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir;
BOOL useMyAppDir = NO;
if([fileManager fileExistsAtPath:myDirPath isDirectory:&isDir]){
if (isDir) {
useMyAppDir = YES;
}
} else {
//create the directory
if([fileManager createDirectoryAtPath:myDirPath withIntermediateDirectories:YES attributes:nil error:nil]){
useMyAppDir = YES;
}
}

if (useMyAppDir) {
NSURL * myAppDirectoryURL = [NSURL URLWithString:myDirPath];
[savePanel setDirectoryURL:myAppDirectoryURL];
}
}
} else {
[savePanel setExtensionHidden:[self fileNameExtensionWasHiddenInLastRunSavePanel]];
}

return YES;
}

最佳答案

在您的 NSDocument 子类中,覆盖 -prepareSavePanel:

- (BOOL) prepareSavePanel:(NSSavePanel *)savePanel 
{
// Set default folder if no default preference is present
NSDictionary *userDefaults = [[NSUserDefaults standardUserDefaults] persistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
if ([userDefaults objectForKey:@"NSNavLastRootDirectory"] == nil) {
NSArray *picturesFolderURLs = [[NSFileManager defaultManager] URLsForDirectory:NSPicturesDirectory inDomains:NSUserDomainMask];
if ([picturesFolderURLs count] > 0) {
NSURL *picturesFolderURL = [[picturesFolderURLs objectAtIndex:0] URLByAppendingPathComponent:@"MyAppName"];
[savePanel setDirectoryURL:picturesFolderURL];
}
}
return YES;
}

关于cocoa - 基于 Cocoa 文档的应用程序中文档的默认保存位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5729363/

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