2014-08-28 65 views
4

完成我有這樣的代碼誰創造iphone我的目錄中的文本文件:操作無法將writeToFile

NSArray *paths = NSSearchPathForDirectoriesInDomains 
    (NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSString *fileName = [NSString stringWithFormat:@"%@/file.txt", 
          documentsDirectory]; 

    NSString *content = @"my first text"; 

    NSError *error; 

    if ([[NSFileManager defaultManager] fileExistsAtPath:fileName] == NO) { 

    [content writeToFile:fileName 
       atomically:YES 
       encoding:NSStringEncodingConversionAllowLossy 
        error:&error]; 

    }else{ 

     [content writeToFile:fileName 
        atomically:YES 
        encoding:NSStringEncodingConversionAllowLossy 
         error:&error]; 

    } 

的代碼是完美的工作,直到在某個時刻它不起作用了,並返回以下錯誤:

Error Domain=NSCocoaErrorDomain Code=517 "The operation couldn’t be completed. (Cocoa error 517.)" UserInfo=0x8c852b0 {NSFilePath=/Users/williamlima/Library/Application Support/iPhone Simulator/7.1/Applications/B5781B9E-3915-4656-83D4-5E0FB6486567/Documents/file.txt, NSStringEncoding=1}

我該如何解決此問題?

回答

5

你可以用UTF8Encoding嘗試

[content writeToFile:fileName 
       atomically:YES 
       encoding: NSUTF8StringEncoding 
        error:&error];