iPhone reading file - strange behavior
so I've got a file called answers.txt
which looks like this:
1:A
2:B
3:BC
......
so a bunch of lines separated by a new line
i use this code to get the lines into a NSArray
:
NSStringEncoding encoding;
NSError* error;
NSString* myString = [NSString stringWithContentsOfFile:filePath usedEncoding:&encoding error:&error];
NSArray *lines = [myString componentsSeparatedByString:@"\n"];
The file is written unix style, so the lines are separated by \n
an开发者_如何转开发d not \r\n
Now for the problem:
When I build on the simulator, I get a correct array of lines if I split at \r\n
and an incorrect array if I split at \n
(I mean it does split at \n
but then I split again every line at :
, the second element has a newline at the end)
When I build on the device, it does exactly the opposite (it splits correctly at \n
, and if I split at \r\n
I get only one element - probably because there is no \r
in the file)
Am I missing something here?
Pretty surprising that simulator and device have different behavior, but you can overcome the problem by using this:
[str componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
Here for the Docs.
精彩评论