我创建了一个基于 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/