2009-11-30 80 views
11

我正在嘗試使用字符串內容創建一個文本文件到我的桌面。我不知道我是否做得對,我沒有得到錯誤,但它也不能工作...Objective-C使用字符串創建文本文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES); 
NSString *desktopDirectory=[paths objectAtIndex:0]; 
NSString *filename = [desktopDirectory stringByAppendingString: @"file.txt"]; 
[myString writeToFile:filename atomically:YES encoding: NSUTF8StringEncoding error: NULL]; 

回答

13

你不知道你是否因爲你'忽略-writeToFile:...方法返回的YES/NO值,並且不給它記錄任何可能的失敗的錯誤指針。如果方法返回NO,那麼您將檢查(並處理或呈現)錯誤以查看錯誤。

根據猜測,失敗是由於您構建的路徑。嘗試-stringByAppendingPathComponent:而不是-stringByAppendingString:...這和它的相關方法正確地處理路徑。

該文件可能是實際上正在創建(即你可能沒有得到任何錯誤)。我的猜測是該文件是在「〜/ Desktopfile.txt」之類的地方創建的,因爲您使用-stringByAppendingString:不會將該字符串視爲以斜槓分隔的路徑。檢查您的主文件夾 - 我會在該文件下注。

39
//Method writes a string to a text file 
-(void) writeToTextFile{ 
    //get the documents directory: 
    NSArray *paths = NSSearchPathForDirectoriesInDomains 
     (NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    //make a file name to write the data to using the documents directory: 
    NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                documentsDirectory]; 
    //create content - four lines of text 
    NSString *content = @"One\nTwo\nThree\nFour\nFive"; 
    //save content to the documents directory 
    [content writeToFile:fileName 
        atomically:NO 
          encoding:NSStringEncodingConversionAllowLossy 
            error:nil]; 

} 
+0

完美的男人......謝謝。 – 2013-06-19 20:57:57

+0

這工作完美 – MayorMonty 2013-10-05 16:07:27

+0

謝謝,隊友!簡單易用。 – Felipe 2017-03-17 21:13:53

-3

問題是桌面目錄字符串以無(no /)結尾。使用UIAlertview檢查(在iPhone上)。

+1

什麼? 1)如果你這樣做,你不需要使用'/'。 2.)你在哪裏看到一個UIAlertView?我不。 3)這個問題在2年前就被問到了。 – 2011-08-14 17:43:58

+0

..我們爲什麼要檢查一下iOS上的「桌面」有什麼用處? iOS沒有這種東西。 – 2015-08-26 00:49:55