我在iPhone中使用以下代码将字符串写入存储在我的iPhone项目资源文件夹中的文件中。当我尝试读取它成功读取数据但当我尝试写它不写文件虽然它的aloso没有给我任何错误。
这是我的代码:
NSString *myString; //Assuume the string you want to write is this
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myfile.txt"];
[myString writeToFile:path atomically:YES];
请任何人指导。
答案 0 :(得分:1)
- (void) testStringReadWrite {
NSString *myString = @"abcd efgh";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myfile.txt"];
CFShow(path);
NSError *error = nil;
[myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(@"%@",error);
}
NSString *readString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(@"%@", error);
} else {
CFShow(readString);
}
}
答案 1 :(得分:0)
writeToFile:atomically:已在iOS 2.0中被删除。使用writeToFile:atomically:encoding:error:相反。您应该检查字符串的内容,例如通过NSLog()函数。不恰当的初始化可能导致失败。
NSLog(@"%@", myString);
[myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
答案 2 :(得分:0)
仅仅是我的两分钱,来自OS X,我习惯于拨打writeToURL()
而不是writeToFile()
。事实证明,writeToFile()
是适用于iOS的。