IOS:将nsarray与字符串同步的问题

时间:2011-07-05 08:51:13

标签: ios xcode nsarray text-files

我有这样的NSArray

myArray[0] = [string1, string2, string3, string4, mySecondArray, string5]; (at 0 position)

我以这种方式在txt文件中写这个数组

NSString *outputString = @"";

for (int i = 0; i< myArray.count; i++){

    outputString =  [outputString stringByAppendingString:[[[myArray objectAtIndex:i ] componentsJoinedByString:@"#"] stringByAppendingString:@";"]];
}

NSLog(@"string to write = %@", outputString);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Text.txt"];
NSError *error;

[outputString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

那么NSLog的结果是=(myArray的位置0)(mySecond数组为空)

one#two#three#four#(
)#five;

我想知道:

  • 为什么数组换行?
  • 当我去阅读这个字符串时,我怎么知道它是mySecondArray?

1 个答案:

答案 0 :(得分:0)

当您在componentsJoinedByString:对象上发送NSArray时,它会在每个对象上调用description并按顺序连接它们。对于NSString个对象,它们本身就是字符串。由于description方法的实现方式,数组会换行。

至于在读回字符串时识别数组,我认为不可能。您应该考虑将数组写入文件,而不是。

[[myArray objectAtIndex:0] writeToFile:filePath atomically:YES];

[myArray writeToFile:filePath atomically:YES];

取决于要求。这样您就可以正确地读取元素。

相关问题