2011-04-20 67 views
1

我已經創建了基於Cocoa文檔的圖片繪製應用程序。我希望在Save/Save As對話框中使用我的應用程序創建的新文檔的默認位置應位於〜/ Pictures/MyAppName /目錄中。默認保存在基於Cocoa文檔的應用程序中文檔的位置

我該如何做到這一點?

我嘗試了或多或少什麼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; 
} 
+0

是否會出問題嗎? 我試過了,但沒有我想要的效果。我覆蓋了 - (BOOL)prepareSavePanel:(NSSavePanel *)savePanel方法並保存了一個文檔後,保存路徑是我以前打開的最後一個過去,並且我總是可以選擇另一個目錄進行保存! – 2012-10-14 18:29:03

回答

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

我曾嘗試過或多或少的建議。我用我的代碼編輯了我原來的帖子。 – AmaltasCoder 2011-04-20 12:50:09

+0

'NSURL * myAppDirectoryURL = [NSURL URLWithString:myDirPath];'是錯誤的。必須是[[NSURL fileURLWithPath:myDirPath];'。另外,你爲什麼不首先與我們分享你的代碼?那會爲我節省很多時間。 – 2011-04-20 12:53:00

相關問題