我有3个NSString
个对象,我想在应用运行时将其保存到新文件中。
这将有助于我进行远程调试!
如果任何人可以帮助我创建文件并将数据保存到它将非常使用
感谢名单
答案 0 :(得分:4)
您可以将文件保存到Documents目录,以下是获取该目录路径的方法:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
示例写声明:
NSError *error;
BOOL status = [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
答案 1 :(得分:4)
在NSString
文档中,有一种名为writeToFile:atomically:encoding:error:
的方法。
NSError *error;
[@"Write me to file" writeToFile:@"<filepath>" atomically:YES encoding: NSUTF8StringEncoding error:&error];
答案 2 :(得分:2)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSError *error; BOOL succeed = [myString writeToFile:[documentsDirectory stringByAppendingPathComponent:@"myfile.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
// Handle error here }
答案 3 :(得分:0)
以下是如何将NSString保存到Documents文件夹中。保存其他类型的数据也可以通过这种方式实现。
- (void)saveString:(NSString *)stringToSave toDocumentsWithFilename:(NSString *)fileName {
NSString *documentsFolder = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *path = [documentsFolder stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] createFileAtPath:path contents:[stringToSave dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
}
用法:
NSString *stringWeWantToSave = @"This is an elephant";
NSString *fileName = [NSString stringWithString:@"savedString.txt"];
[self saveString:stringWeWantToSave toDocumentsWithFilename:fileName];