2011-06-05 59 views
4

我需要在啓動時顯示位於用戶桌面上的NSTextView文本文件的內容。我的代碼不起作用 - 是不是跟蹤?在應用啓動時從桌面讀取文本文件

NSError *err = nil; 

NSString *filepath = @"~/Desktop/test.txt"; 

NSString *file = [NSString stringWithContentsOfFile:filepath 
              encoding:NSUTF8StringEncoding 
               error:&err]; 

if(!file) { 

} 

[textView setString:file]; 
+0

我得到了它;)忘記:文件路徑= [文件路徑stringByExpandingTildeInPath]感謝 – Paul 2011-06-05 05:00:11

+1

你應該張貼,作爲一個答案。 – 2011-06-05 05:14:46

+0

它應該作爲答案發布,但新用戶限制可能會阻止這種情況發生,直到明天。 @Peter – 2011-06-05 05:30:35

回答

7

@Shem。對於那個很抱歉。

我固定它是這樣的:

NSError *err = nil; 

NSString *filepath = @"~/Desktop/test.txt"; 
filepath = [filepath stringByExpandingTildeInPath]; 

NSString *file = [NSString stringWithContentsOfFile:filepath 
             encoding:NSUTF8StringEncoding 
              error:&err]; 

if(!file) { 

} 

[textView setString:file]; 
+0

您應該將您的帖子標記爲已接受的答案。 – 2011-06-05 21:07:17

0

你的文本文件的路徑看起來關閉...可能是:/Users/USERNAME/Desktop/test.txt另外,儘量NSLog(@"Error: %@",[err description]);,看看會產生什麼錯誤。

+3

〜是用戶主目錄的縮寫,通常位於「/ Users/USERNAME」。你建議提問者應該嘗試訪問/Users/USERNAME/Users/USERNAME/Desktop/test.txt,這是不正確的。 – 2011-06-05 05:14:34

+2

@保羅 - 你爲什麼接受不正確的答案?給它一些時間 - 沒有規則說你必須接受發佈的第一個答案。 – 2011-06-05 06:53:49