2013-02-14 69 views
1

我正在製作一個OX Cocoa應用程序,我希望能夠使用按鈕按下應用程序來讀寫文本文件。這些文本文件應該保存在/ Library/Application Support/AppName中,但是我無法讓我的應用程序從那裏讀取任何內容。它可以寫入文件夾,但不會讀取它寫入的內容,即使我可以在查找器中看到文件。如何從/庫/應用程序支持/文件夾中讀取?

這裏是我使用的成功寫入到該文件夾​​中的代碼。

NSString *text = editor.string; 
    NSString *path = @"/Library/Application Support/"; 

    NSMutableString *mu = [[NSMutableString stringWithString:path] init]; 
    [mu insertString:FileName.stringValue atIndex:mu.length]; 
    [mu insertString:@".txt" atIndex:mu.length]; 

    path = [mu copy]; 
    [text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL]; 

這是我使用(和失敗)從文本文件中讀取的代碼。

NSArray *path = [[NSBundle mainBundle] pathsForResourcesOfType:@"txt" inDirectory:@"/Library/Application Support/"]; 
    NSString *output = @""; 

    NSMutableString *mu = [[NSMutableString stringWithString:output] init]; 

    for (int i = 0; i < [path count]; i++) { 
     NSString *text = [NSString stringWithContentsOfFile:path[i] encoding:NSUTF8StringEncoding error:NULL]; 
     [mu insertString:text atIndex:mu.length]; 
     [mu insertString:@"\n" atIndex:mu.length]; 
    } 

    [textView setString:mu]; 

我能糾正的任何提示都會超級有用,我有點卡在這裏。

編輯:使用您輸入我已經更新了我的代碼如下:

NSString *fileLocation = @"~/Library/Application Support/"; 
    NSArray *text = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fileLocation error:nil]; 
    NSString *output = @""; 
    NSMutableString *mu = [[NSMutableString stringWithString:output] init]; 

    for (int i = 0; i < [text count]; i++) { 
     [mu insertString:text[i] atIndex:mu.length]; 
     [mu insertString:@"\n" atIndex:mu.length]; 
    } 
    [textView setString:mu]; 

但是從文件的文本仍然沒有出現。

回答

0

/庫/應用程序支持是不是在你的包。您使用[[NSBundle mainBundle] pathsForResourcesOfType:…]獲得的路徑僅用於訪問應用程序本身內的文件(圖像,聲音等,您在構建應用程序時包含的內容)。

你想用[[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:error]讓您的應用程序之外的目錄中的文件列表。

馬特·加拉格爾具有Cocoa With Love定位路徑到您的應用程序支持目錄的容錯方法的一個很好的例子。我建議使用它來硬編碼/ Library/Application Support路徑。

NSError *error = nil; 
NSArray *text = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fileLocation error:&error]; 
if (!text) { 
    NSLog(@"Error reading contents of application support folder at %@.\n%@", applicationSupportFolder, [error userInfo]); 
} 
+0

在您的原始代碼中編寫您指向/ Library/Application Support的文件。你有沒有改變它以匹配你在這裏使用的〜/ Library/Application Support? – 2013-02-14 22:07:30

+0

是否有所作爲? – 2013-02-14 22:09:01

+1

是的。 〜擴展爲/ Users/*用戶名*/Library/Application Support,不帶〜進入全局/庫/應用程序支持文件夾。 – 2013-02-14 22:09:52

0

你試圖從應用程序的主包中獲取使用NSBundle的路徑。但該文件不在包中,您應該手動指定路徑。您可以對路徑進行硬編碼,將以前寫入的路徑存儲在某處,或使用NSFileManager獲取目錄內容並對其進行分析。例如,-[NSFileManager contentsOfDirectoryAtPath:error:]。當你Sandbox中的應用

1

大多數硬編碼路徑將失敗。即使你逃避了這個,或者你不打算沙盒這個應用程序,這是一個值得離開的壞習慣。

而且,你確定你想/Library而不是~/Library?前者通常不能被用戶寫入。後者位於用戶的主目錄中(或沙盒時的容器)。

獲取應用程序支持目錄或Caches目錄或任何其他目錄,您可能想要創建它們並稍後從ask a file manager for it中檢索它們。

相關問題