Cocoa文档型应用程序中文档的默认保存位置

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

这里出了问题吗? 我尝试过了,但它没有我想要的效果。 在我重写 - (BOOL) prepareSavePanel:(NSSavePanel *)savePanel 方法并保存文档后,保存路径是我之前打开的最后一个路径,我总是可以选择另一个目录进行保存! - Jet Li
1个回答

4
在您的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;
}

我已经尝试了你建议的大部分内容。我编辑了我的原始帖子并附上了我的代码。 - AmaltasCoder
NSURL * myAppDirectoryURL = [NSURL URLWithString(myDirPath)]; 是错误的。必须使用 [NSURL fileURLWithPath:myDirPath];。另外,你为什么不在一开始就和我们分享你所拥有的代码呢?这样做可以节省我很多时间。 - Ole Begemann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接