views:

1863

answers:

4

If I have an NSString with a text file in it, how do I get an NSArray of NSString with each NSString containing a line of the file.

In 10.5 I did this:

NSArray* lines = [str componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];

But that doesn't work in 10.4, and my program needs to work in 10.4.

As well, it needs to work with \r, \n and \r\n line endings.

+1  A: 

According to the NSString class reference, the NSString message componentsSeparatedByCharactersInSet: is available in OS X 10.5 or later. You need to use componentsSeparatedByString:.

J. John
Sorry, I didn't tell you how to do it, just why your solution doesn't work in 10.4.
J. John
+4  A: 
e.James
I compiles without warnings when the target is set to 10.4 and it works well. Thanks.
FigBug
+2  A: 

Straight from a project of mine:

NSString * fileContents = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:nil];

NSMutableArray * fileLines = [[NSMutableArray alloc] initWithArray:[fileContents componentsSeparatedByString:@"\r\n"] copyItems: YES];

I'm not sure how to make it it automatically work with any type of line ending in 10.4.

Rich Catalano
+3  A: 

I'll first replace all "\r" with "\n", then replace all "\n\n" with "\n", and then do a componentsSeparatedByString:@"\n".

Heng-Cheong Leong
Not the most efficient solution, but +1 for being clever about it
e.James