2013-05-10 69 views
2

拉我的頭髮試圖解決這個問題。我想在我的項目中讀取和寫入一個數字列表到一個txt文件。然而[字符串writeToFile:原子路徑:是編碼:NSUTF8StringEncoding錯誤:&錯誤]似乎沒有寫入任何文件。我可以看到路徑字符串返回一個文件路徑,所以它似乎找到了它,但似乎沒有寫入任何文件。將字符串寫入目標c中的txt文件

+(void)WriteProductIdToWishList:(NSNumber*)productId { 

    for (NSString* s in [self GetProductsFromWishList]) { 
     if([s isEqualToString:[productId stringValue]]) { 
      //exists already 
      return; 
     } 
    } 

    NSString *string = [NSString stringWithFormat:@"%@:",productId]; // your string 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"WishList" ofType:@"txt"]; 
    NSError *error = nil; 
    [string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error]; 
    NSLog(@"%@", error.localizedFailureReason); 


    // path to your .txt file 
    // Open output file in append mode: 
} 

編輯:路徑示出了如/var/mobile/Applications/CFC1ECEC-2A3D-457D-8BDF-639B79B13429/newAR.app/WishList.txt所以確實存在。但是回頭看看:

NSString *path = [[NSBundle mainBundle] pathForResource:@"WishList" ofType:@"txt"]; 

只返回一個空字符串。

+0

是否有任何特定的要求來將信息寫入txt本身。如果你把它寫成plist以便使用,這會更好。 – Anupdas 2013-05-10 17:03:08

+0

是否要將這些文件存儲在與項目主目錄相關的子目錄中? – nzs 2013-05-10 18:08:40

回答

10

您正嘗試寫入應用程序包內的位置,該位置不能被修改,因爲該包是隻讀的。您需要找到可寫入的位置(在應用程序的沙箱中),然後在撥打string:WriteToFile:時,您會得到您期望的行爲。

通常應用程序會在首次運行時從軟件包中讀取資源,將所述文件複製到合適的位置(嘗試文檔文件夾或臨時文件夾),然後繼續修改文件。

因此,例如,沿着這些路線的東西:

// Path for original file in bundle.. 
NSString *originalPath = [[NSBundle mainBundle] pathForResource:@"WishList" ofType:@"txt"]; 
NSURL *originalURL = [NSURL URLWithString:originalPath]; 

// Destination for file that is writeable 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSURL *documentsURL = [NSURL URLWithString:documentsDirectory]; 

NSString *fileNameComponent = [[originalPath pathComponents] lastObject]; 
NSURL *destinationURL = [documentsURL URLByAppendingPathComponent:fileNameComponent]; 

// Copy file to new location 
NSError *anError; 
[[NSFileManager defaultManager] copyItemAtURL:originalURL 
             toURL:destinationURL 
             error:&anError]; 

// Now you can write to the file.... 
NSString *string = [NSString stringWithFormat:@"%@:", yourString]; 
NSError *writeError = nil; 
[string writeToFile:destinationURL atomically:YES encoding:NSUTF8StringEncoding error:&error]; 
NSLog(@"%@", writeError.localizedFailureReason); 

展望未來(假設你想繼續隨時修改該文件),你需要評估是否在文件中已經存在用戶的文檔文件夾,確保只在需要時從軟件包複製文件(否則每次都會用原始軟件包副本覆蓋修改後的文件)。

2

爲了避免寫入特定目錄中的文件造成的麻煩,請使用NSUserDefaults類來存儲/檢索鍵值對。這樣,當你64歲時,你仍然會有頭髮。

+0

NSUserDefaults是一個不錯的選擇。有關介紹性的SO幫助,請查看我接受的答案,並在NSUserDefaults上使用有用的代碼片段:http://stackoverflow.com/questions/16475300/storing-results-after-screen-is-disappear/16476022#16476022 – nzs 2013-05-10 18:03:06

+0

NSUserDefaults可能是一個很好的但這個問題(至少對我而言)意味着應用程序包中的文本文件可能已經被填充了數據。 – isaac 2013-05-10 20:25:36