xcode IOS:从数组中将字符串写入文件txt
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6569432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IOS: write a string in a file txt from an array
提问by cyclingIsBetter
I have an array composed by other array:
我有一个由其他数组组成的数组:
example my array with two arrays inside:
例如我的数组里面有两个数组:
myArray = [(element1, element2, element3)],[(element4,element5,element6)] this is only an example to show that myArray have two arrays (these elements are string)
myArray = [(element1, element2, element3)],[(element4,element5,element6)] 这只是一个例子来说明 myArray 有两个数组(这些元素是字符串)
now I want write in a txt file these elements in this way:
现在我想以这种方式在 txt 文件中写入这些元素:
element1#element2#element3;element4#element5#element6;
what is the code to create this string to write in txt file?
创建此字符串以写入 txt 文件的代码是什么?
回答by Dileep Reghu
NSMutableString *printString = [NSMutableString stringWithString:@""];
for(i=0;i<[myArray count];i++)
{
for (NSString element in [myArray objectAtIndex:i])
{
[printString appendString:[NSString stringWithFormat:@"%@#",element] ];
}
[printString appendString:@";"];
}
//CREATE FILE
NSError *error;
// Create file manager
//NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory()
stringByAppendingPathComponent:@"Documents"];
NSString *filePath = [documentsDirectory
stringByAppendingPathComponent:@"fileArray.txt"];
NSLog(@"string to write:%@",printString);
// Write to the file
[printString writeToFile:filePath atomically:YES
encoding:NSUTF8StringEncoding error:&error];