[英]Not able to write into text file
我需要將字符串寫入文件。 為此,我的代碼是:
-(void)writeToFile:(NSString *)fileName: (NSString *)data {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
[data writeToFile:appFile atomically:YES];
}
我這樣調用這個方法
ownServices *obj = [[ownServices alloc]init];
[obj writeToFile:@"iphone.txt" :@"this is mahesh babu"];
但它沒有寫入文本文件。
什么原因? 誰能幫幫我嗎。
提前謝謝你。
最可能的問題是文檔目錄不存在。 如果沒有,則創建它,然后寫入它:
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *parentDir = [paths objectAtIndex:0];
/* Create the parent directory.
* This is expected to fail if the directory already exists. */
(void)[[NSFileManager defaultManager]
createDirectoryAtPath:parentDir
withIntermediateDirectories:YES
attributes:nil error:NULL];
NSString *path = [parentDir stringByAppendingPathComponent:fileName];
/* Now write, and if it fails, you'll know why thanks to the |error| arg. */
NSError *error = nil;
BOOL ok = [data writeToFile:path options:NSDataWritingAtomic error:&error];
if (!ok) {
NSLog(@"%s: Failed to write to %@: %@", __func__, path, error);
}
更簡單的是使用最新的 API,如果它不存在,它將為您創建目錄:
NSError *error = nil;
NSURL *parentURL = [[NSFileManager defaultManager]
URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask
appropriateForURL:nil create:YES error:&error];
if (!parentURL) {
NSLog(@"%s: *** Failed to get documents directory: %@", __func__, error):
return;
}
NSURL *furl = [parentURL URLByAppendingPathComponent:fileName];
error = nil;
BOOL ok = [data writeToURL:furl options:NSDataWritingAtomic error:&error];
if (!ok) {
NSLog(@"%s: *** Failed to write to %@: %@", __func__, furl, error);
}
首先,您奇怪地調用了您的方法。 將方法重命名為
-(void)writeString:(NSString *) data toFile:(NSString *)fileName
並這樣稱呼它:
[obj writeString:@"this is mahesh babu" toFile:@"iphone.txt"];
其次,不推薦使用 writeToFile:atomically writeToFile:atomically:
使用writeToFile:atomically:encoding:error:
:
NSError *error = nil;
BOOL success = [data writeToFile:appFile atomically:YES encoding:NSUTF8Encoding error:&error];
if (!success) {
NSLog(@"Error: %@", [error userInfo]);
}
這樣,您還可以看到錯誤是什么。
您的代碼看起來不錯。 使用調試器(或NSLog
語句)來驗證data
和appFile
的值。 如果data
為nil
,則不會發生任何事情(包括沒有錯誤),因為向nil
發送消息是無操作的。 appFile
也可能不是您認為的路徑。
檢查您嘗試寫入的目錄的權限( ls -la
)。 在設備上你不能,但在模擬器上你可以。 它對您來說是只讀的嗎? 它是否由其他用戶擁有?
假設這不是問題,請嘗試使用atomically:NO
調用。 原子文件寫入是通過寫入一個文件,然后將其重命名以替換舊文件來執行的。 如果問題存在,那將隔離問題。
OwnServices
而不是ownServices
writeToFile:string:
這樣的名稱會更好。data
旨在指向NSData
以外的某個實例,請不要命名它。 這很令人困惑,除了“數據”之外,您幾乎可以使用一個更好(更具體)的詞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.