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

时间:2011-04-20 11:18:16

标签: cocoa macos

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

1 个答案:

答案 0 :(得分:2)

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